gpt4 book ai didi

java - 如何从 adapter.java 中的 ListView 设置 Onclick ImageView

转载 作者:行者123 更新时间:2023-11-29 04:16:06 26 4
gpt4 key购买 nike

我的问题是关于“如何从 ListView 设置 OnClick ImageView”

适配器.java

public class Adapter extends BaseAdapter implements OnClickListener{

Context context;
ArrayList<Contact> list;
LayoutInflater inflater;

public Adapter(Context context, ArrayList<Contact> list) {
super();
this.context = context;
this.list = list;
this.inflater =
LayoutInflater.from(context);
}

public View getView(int arg0, View arg1, ViewGroup arg2) {
ContactView pv=null;
if(arg1==null)
{
arg1= inflater.inflate(R.layout.additem, null);
pv = new ContactView();
pv.iv=(ImageView) arg1.findViewById(R.id.imageView1);
pv.name=(TextView) arg1.findViewById(R.id.textView1);
pv.number=(CheckedTextView) arg1.findViewById(R.id.checkedTextView1);
pv.message=(ImageView) arg1.findViewById(R.id.imageView2);
arg1.setTag(pv);
}
else
{
pv=(ContactView) arg1.getTag();
pv.iv.setImageURI(
list.get(arg0).getImage());
pv.name.setText( list.get(arg0).getName());
pv.number.setText( String.valueOf(list.get(arg0).getNumber()));
pv.message=(ImageView)
arg1.findViewById( R.id.imageView2);
pv.message.setOnClickListener( this);
return arg1;
}
}

static class ContactView{
ImageView iv;
TextView name;
CheckedTextView number;
ImageView message;
}
}

当我从 ListView 中设置点击消息(ImageView)时,它说

“致命异常:主要”

“无法启动 Activity ”

"java.lang.NullPointerException"

.
MainActvity.java

ArrayList<Contact> list = new ArrayList<Contact>();
Adapter adapter;
ImageView message;

protected void onCreate(Bundle savedInstanceState) {
this.lv = (ListView) this.findViewById(R.id.listView1);

this.adapter=new MyAdapter(this,list);
this.lv.setAdapter(adapter);

}

public void onClick(View arg0) {
// TODO Auto-generated method stub
Toast.makeText(this, "sample", Toast.LENGTH_SHORT).show();
}

有人可以帮我如何从 ListView 中设置点击消息(ImageView)??谢谢

最佳答案

我认为你应该在适配器内部设置取消点击...在每个项目上, Activity 在开始时不会找到该 View

有点像

pv.message.setClickable(true);
pv.message.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
Toast.makeText(arg0.getContext(), "sample", Toast.LENGTH_SHORT).show();
}
});

关于java - 如何从 adapter.java 中的 ListView 设置 Onclick ImageView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52323109/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com