我怎样才能引用另一个类的对象

时间:2017-05-04 18:59:07

标签: java android

我正在尝试在我的一个类中创建一个方法,以便在整个项目中使用,建议是显示警告。

我可以在每个班级中创建警报并使用以下代码加班:

AlertDialog.Builder alert = new AlertDialog.Builder(this);

如果正确this引用当前的类对象

如何引用调用alert方法的类的对象?所以我只使用上面的代码一次并从不同的类中调用它

2 个答案:

答案 0 :(得分:2)

您通常会将此代码放在一个以Context对象作为参数的方法中,然后按名称而不是'这个'来引用该参数。

public class Dialogs {

    public AlertDialog createAlert(Context context) {
        AlertDialog.Builder alert = new AlertDialog.Builder(context);
        //etc...
    }

}

答案 1 :(得分:0)

您可以将上下文作为方法参数传递,或者供以后使用,您可以在构造函数中传递Context,并在该类中保留引用并随时使用。

public class MyClass {

  Context context;

  public MyClass(Context context){
    this.context=context;
  }


  public void createDialog(){

      AlertDialog.Builder alert = new AlertDialog.Builder(context);
  }
}

或从上下文(有上下文)类直接调用

public void createDialog(Context context){

   AlertDialog.Builder alert = new AlertDialog.Builder(context);
}