2013-06-04 26 views
1

我想要顯示一個對話框,只要有人點擊自定義列表視圖中的某一行的圖像。我應該如何去做這件事?以下是我在自定義適配器中實現的內容。請參閱「如何在代碼中顯示對話框片段???」的評論。如何在自定義適配器中顯示對話框片段?

public class DirectoryAdapter extends BaseAdapter { 

private Context mContext; 
private final Session mSession; 
private final ArrayList<MyObject> mMyObjects; 

public DirectoryAdapter(Context context, Session session, ArrayList<MyObject> myObjects) { 
    mContext = context; 
    mSession = session; 
    mMyObjects= myObjects; 
} 

    public View getView(int position, View convertView, ViewGroup parent) { 

    LayoutInflater inflater = (LayoutInflater) mContext 
     .getSystemService(Context.LAYOUT_INFLATER_SERVICE); 

    View view = null; 

    try { 
     if (convertView == null) { 

      view = new View(mContext); 
      // get row item from directory_item.xml 
      view = inflater.inflate(R.layout.server_row, null); 
      view.setLongClickable(true); 
     } else { 
      view = (View) convertView;    
     } 

     //Info button 
     ImageView info = (ImageView) view.findViewById(R.id.iv_directory_item_options); 

     info.setOnClickListener(new OnClickListener() { 
      @Override 
      public void onClick(View view) { 
         ServerMenuDialog dialog = new ServerMenuDialog(); 
       dialog.setRetainInstance(true); 
// How to show dialog fragment ??? 
         dialog.show(view.getContext(), "Server Menu"); //EXAMPLE -- WONT COMPILE there is no such view.getContext() method 
      } 

     }); 

    } catch (Exception ex) { 
     //TODO error handling 
    } finally { 
     return view; 
    } 


} 
+0

爲什麼不使用this.context而不是view.getContext()? – Codeman

+0

@Pheonixblade小改正:this.mContext – Marek

+0

@Pheonixblade - this.mContext不是此調用的適當範圍。 'This'似乎引用視圖而不是DirectoryAdapter類。我似乎無法從'mContext'獲得對FragmentManager的引用,所以我有點難住。 – user1532208

回答

0

我不知道是否從適配器類中顯示對話框是一個好主意。我認爲你應該爲你的活動類重寫OnClick方法並實現OnItemClickListener。當你點擊listView元素時,這工作正常。我不確定區分所選元素的哪個視圖是否真的很好(因爲我知道您只是對點擊圖片感興趣),但您可能會發現這一點。不管怎麼說,你應該添加

listView.setOnItemClickListener(this); 


在我aplication我使用下面的代碼:

@Override 
public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) { 

    //Change part below with your code 
    FragmentTransaction fragmentTransaction = callback.fragmentManager.beginTransaction(); 
    fragmentTransaction.setCustomAnimations(android.R.animator.fade_in, android.R.animator.fade_out); 
    ObjectFragment fragment = new ObjectFragment(); 

    Bundle bundle = new Bundle(); 
    bundle.putInt("position", position); 
    fragment.setArguments(bundle); 

    fragmentTransaction.replace(R.id.activity_log_reader_relativeLayout1, fragment); 
    fragmentTransaction.addToBackStack(null); 
    fragmentTransaction.commit(); 
    //---End of change 
} 

在你的情況,而不是創建一個新片段,您應該創建新的對話框。

+1

什麼是'callback'? –

相關問題