2012-08-28 29 views
0

這裏是我的Activity一個非常簡化的版本:如何從AlertDialog的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實例),以便我可以訪問它的方法和變量。

謝謝。

回答

4

使用Search.this.objAdapter到從監聽器訪問objAdapter應該工作。

Search.this指的是當前實例Search並允許您訪問其字段和方法。

1

讓您的活動實現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);