Activity switch case 上下文

Activity context in switch case

我想使用在所有活动中使用的通用进度条。这可以通过检查 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 语句来匹配条件。

A switch works with the byte, short, char, and int primitive data types. It also works with enumerated types, the String class, and a few special classes that wrap certain primitive types: Character, Byte, Short, and Integer (discussed in Numbers and Strings).

你可以这样做:

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

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

注意: 仅在 JDK 之后添加了对 switch 的字符串支持 7. 如果您使用的是 Java 的早期版本,您可以使用一些破解上述内容以使开关正常工作。 this question.

答案中的一些示例