如何在自定义适配器中显示对话框片段?

时间:2013-06-04 23:58:43

标签: android android-fragments

每当有人点击自定义列表视图中某一行的图片时,我想显示一个对话框。我该怎么做呢?这是我到目前为止在我的自定义适配器中实现的内容。请参阅代码中的“如何显示对话框片段??? ”注释我感到难过。

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;
    }


}

1 个答案:

答案 0 :(得分:0)

我不确定在适配器类中显示Dialog是否是个好主意。我认为您应该覆盖活动类的OnClick方法并实现OnItemClickListener。单击listView元素时,这可以正常工作。我不确定区分您实际点击的所选元素的哪个视图也是好的(据我所知您只是对点击图像感兴趣),但您可能会发现这一点。无论如何,你应该添加

listView.setOnItemClickListener(this);


在我的应用程序中,我使用以下代码:

@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
}

在您的情况下,您应该创建新的Dialog。

,而不是创建新的片段