Java 确定上下文是否是特定活动

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21453254/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 08:47:34  来源:igfitidea点击:

Determine if context is a Specific Activity

javaandroidandroid-activityandroid-context

提问by Memento

I'm passing the Activity context to a dialog but that dialog is global to other Activities, so its possible that other activities create that dialog too. My question is how can I determine that Activity context is a specific Activity?

我将 Activity 上下文传递给一个对话框,但该对话框对于其他 Activity 是全局的,因此其他活动也可能创建该对话框。我的问题是如何确定 Activity 上下文是特定的 Activity?

I'm passing ActivityContext like this :

我像这样传递 ActivityContext :

private Activity ActivityContext;

public MessageDialog(Activity context,int DialogStyle,int Dialog_Layout,String Msg) 
{
    super(context,DialogStyle,Dialog_Layout);
    this.ActivityContext = context;
    this.Msg = Msg;
}

采纳答案by marcinj

You can use instanceof:

您可以使用 instanceof:

if ( this.ActivityContext instanceof MyActivity ) {
 /// ....
}

回答by surga

I know the question is in java but if you are looking the answer in the kotlin :

我知道问题出在 Java 中,但如果您正在 kotlin 中寻找答案:

if (this.activity is AppActivity) {
    // ...
}

回答by Biplob Das

override fun onAttach(context: Context) {
    super.onAttach(context)
    if (context is MyInterFace) {
        interfaceVariable = context as MyInterFace
    }
}