簡體   English   中英

我如何引用另一個類的對象

[英]how can I refer to an object of another class

我試圖在我的一個類中創建一個方法,以在整個項目中使用,建議是顯示警報。

我可以在每個班級中創建警報,並超時使用以下代碼:

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

如果正確, this指向當前的類對象

如何引用正在調用alert方法的類的對象? 這樣我只使用上面的代碼一次,然后從不同的類中調用它

您通常會將這段代碼放在以Context對象作為參數的方法中,然后通過名稱而不是'this'引用該參數。

public class Dialogs {

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

}

您可以將上下文作為方法參數傳遞,或者供以后使用,可以在構造函數中傳遞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);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM