[英]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.