[英]How can I access my Activity's instance variables from within an AlertDialog's onClickListener?
這是我的Activity
的非常簡化的版本:
public class Search extends Activity {
//I need to access this.
public SearchResultsAdapter objAdapter;
public boolean onOptionsItemSelected(MenuItem itmMenuitem) {
if (itmMenuitem.getItemId() == R.id.group) {
final CharSequence[] items = {"Red", "Green", "Blue"};
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle(itmMenuitem.getTitle());
builder.setSingleChoiceItems(lstChoices),
0, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
//I need to access it from here.
}
});
AlertDialog alert = builder.create();
alert.show();
return true;
}
}
}
當按下菜單按鈕時,我的應用程序將彈出AlertDialog
。 當創建AlertDialog
和在線onClickListener
被附接到每個對話框中的項目。 我需要訪問在Search
活動中定義的objAdapater
變量。 我無權訪問onClickListener
的搜索實例,因此無法訪問它。 在隨處都傳遞Activity
實例的情況下,我的代碼有些麻煩。 也許我做錯了。
我如何從onClickListener
內訪問Activity
( Search
實例),以便可以訪問它的方法和變量。
謝謝。
使用Search.this.objAdapter
從偵聽器訪問objAdapter
應該可以工作。
Search.this
指向Search
的當前實例,並允許您訪問其字段和方法。
使您的活動實現OnClickListener:
public class Search extends Activity implements DialogInterface.OnClickListener { ...
將onclick方法添加到您的活動中:
public void onClick(DialogInterface dialog, int item) {
//I need to access it from here.
}
然后將您的活動作為偵聽器傳遞:
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle(itmMenuitem.getTitle());
builder.setSingleChoiceItems(lstChoices),0, this);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.