如何从OnItemClickListener中使用imageView?

时间:2016-11-18 09:01:45

标签: java android listview clickable-image

lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(final AdapterView<?> parent, View view, final int position, long id) 
        {

         // My code is here. I want make my image clickable. I don't want make it clickable in my CustomAdapter getView() method because it doesn't allows me open DialogFragment from there.
         // I already setted in xml of image clickable="true" and focusable = "false"
         //I'll admit for any help and thanks in advance

        }
}

3 个答案:

答案 0 :(得分:3)

如果从适配器中获取图像Onclick,则无法从listview事件中获取setOnItemClickListener。我建议您可以使用Onclick而不是setOnItemClickListener从适配器获取Onclick。

答案 1 :(得分:1)

首先,您必须在适配器类中为Imageview添加OnClickListener,例如

viewHolder.button1.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {
    ((ListView) parent).performItemClick(v, position, 0); // Let the event be handled in onItemClick()
}

});

然后您可以在onItemClick中访问ImageView

@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
    long viewId = view.getId();


if (viewId == R.id.button1) {
        Toast.makeText(this, "Button 1 clicked", Toast.LENGTH_SHORT).show();
    } else if (viewId == R.id.button2) {
        Toast.makeText(this, "Button 2 clicked", Toast.LENGTH_SHORT).show();
    } else {
        Toast.makeText(this, "ListView clicked" + id, Toast.LENGTH_SHORT).show();
    }
}

享受!...

答案 2 :(得分:0)

从适配器显示对话框应该不是问题。如果您的适配器需要它没有的东西,那么您可以使用private final OnImageClickListener之类的监听器为适配器添加一个字段并创建一个接口:

public interface OnImageClickListener {
    void onImageClicked(View view, int position, int id);
}

当您从活动或片段创建适配器时,您可以在activity / fragment中或匿名类中实现此接口,并且在那里您可以访问片段管理器并可以执行任何操作。< / p>