【问题标题】:Activity context in switch case切换案例中的活动上下文
【发布时间】:2016-01-02 10:48:46
【问题描述】:

我想使用所有活动中使用的通用进度条。这可以通过检查 if else 语句来完成,例如

if(mContext instanceOf ActivityA)
   {
     //Do Something   
   }else if(mContext instanceOf ActivityB)
   {
    //Do Something
   }

但我想做类似的事情:

switch(mContext){
case mContext instaceOf ActivityA:
                    //Do Something
case mContext instanceOf ActivityB:
                    //DoSomething
}

如何通过检查 switch 中的上下文来实现

【问题讨论】:

  • switch 不能用于匹配条件,只能用于值。
  • 是的,我想使用所有活动通用的进度条,我只需将上下文和值传递给它。
  • @sparta 。 - 那么有什么好的方法来检查上下文而不是 if else 语句。
  • 我认为if/elses 在这种情况下很好。
  • FWIW,可能有比冗长的if..else... 声明更好的方法。例如,听起来您可以拥有一个基 Activity,其中 ActivityAActivityB 扩展,以及一个被调用的 abstract 方法。

标签: android android-activity switch-statement


【解决方案1】:

你可以这样做:

String className = mContext.getClass().getSimpleName();

switch (className) {
  case "ActivityA":
     //Do Something
  case "ActivityB":
     //DoSomething
}

注意: 仅在 JDK 7 之后才添加了对 switch 的字符串支持。如果您使用的是 Java 的早期版本,则可以使用上面的一些技巧来使 switch 工作。 this question 的答案中的一些示例。

【讨论】:

    【解决方案2】:

    您不能使用switch 语句来匹配条件。

    开关适用于 byteshortcharint 原始数据 类型。它也适用于枚举类型String 类,以及一些包装某些特定类的特殊类 原始类型:Character、Byte、Short 和 Integer(在 数字和字符串)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多