2012-05-03 32 views

回答

1

我沒有看到你遇到問題的地方。如果你有你的BaseAdapter版本在Activity A然後你可以簡單地調用(在OnCLickListener爲你的BaseAdaptergetView方法來設置該行的項目),你在A Activity創建一個私有方法:

private void showADialog(int position) { 
     new AlertDialog.Builder(this) 
       .setMessage("The clicked row is " + position) 
       .setPositiveButton("Ok?", 
         new DialogInterface.OnClickListener() { 

          @Override 
          public void onClick(DialogInterface dialog, 
            int which) { 
           dialog.dismiss(); 
          } 

         }).show(); 
    } 

如果您的自定義BaseAdapterActivity A不在同一個文件中,那麼您可以使用傳遞給BaseAdapterContext(如果適配器的代碼是上一個問題中的代碼,那麼您應該將它傳入構造函數)。然後,您可以將該Context投射到您的活動中,並調用以前的方法showADialog()。再次

//... 
item.setTag(new Integer(position)); // or if you use a ViewHolder: holder.item bla..... 
item.setOnClickListener(new OnClickListener() { 
    @Override 
    public void onClick(View v) { 
    Integer realPosition = (Integer) v.getTag(); 
    // Here show the dialog using one of the methods above.You either:   
    // showADialog(realPosition); // when the code for your custom BaseAdapter in in the same class as Activity A 
    //((CallingAlertDialogBaseAdapter) context).showADialog(realPosition); // when the code for the custom BaseAdapter is in a separate file then Activity A 
    //create directly an AlertDialog. For this you'll require a valid Context(from an Activity(getApplicationCOntext() will NOT work). 
    //You have this context from the parameter that you pass in the constructor of your custom BaseAdapter(as you ussualy pass this in the Activity where you instantiate the adapter) 
    } 
}); 
//... 
+0

感謝:此外,當您設定的聽衆,你應該通過position的標籤,所以你可以在OnCLickListener找回它(否則你會得到錯誤的位置的看法+聽者得到回收)。是的,它和我的其他帖子是一樣的代碼。我最終爲我的History類添加了'BaseAdapter',因爲'mContext'導致了'NullPointerException' - 我的'DialogInterface'在一個單獨的類中,我試圖通過通過'History'' Activity'類'BaseAdapter'。 – gatzkerob