簡體   English   中英

如何從AlertDialog的onClickListener中訪問Activity的實例變量?

[英]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內訪問ActivitySearch實例),以便可以訪問它的方法和變量。

謝謝。

使用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.

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