2

每当有人从自定义列表视图中的某一行单击图像时,我想显示一个对话框。我该怎么做呢?这是我迄今为止在我的自定义适配器中实现的。请参阅代码中的“如何显示对话框片段??? ”注释,了解我难过的地方。

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


}
4

1 回答 1

0

我不确定从适配器类中显示对话框是否是个好主意。我认为您应该改写您的活动类的 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
}

在您的情况下,您应该创建新的对话框,而不是创建新的片段。

于 2013-06-05T00:03:45.680 回答