如果ListView中的项内部有Clickable视图,则这些视图将首先捕获点击事件,并阻止OnClick事件传递到ListView的OnItemClickListener。要解决此问题,您可以在ListView的适配器中设置Clickable视图的点击监听器,并在onItemClick()回调方法中添加适当的处理函数。以下是一个示例代码:
public class MyAdapter extends ArrayAdapter
...
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = convertView;
ViewHolder holder;
if (view == null) {
view = LayoutInflater.from(context).inflate(R.layout.list_item, parent, false);
holder = new ViewHolder();
holder.textView = view.findViewById(R.id.text);
holder.button = view.findViewById(R.id.button);
view.setTag(holder);
} else {
holder = (ViewHolder) view.getTag();
}
final MyItem item = getItem(position);
holder.textView.setText(item.getText());
holder.button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// do something
}
});
holder.textView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// do something
}
});
return view;
}
private static class ViewHolder {
TextView textView;
Button button;
}
}
在您的ListView上设置OnItemClickListener,然后在onItemClick()回调方法中添加适当的处理函数:
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView> parent, View view, int position, long id) { // do something MyItem item = (MyItem) parent.getItemAtPosition(position); Toast.makeText(MainActivity.this, item.getText(), Toast.LENGTH_SHORT).show(); } });
在这个示例代码中,我们在ListView的适配器中将Clickable视图的点击事件监听器设置为ViewHolder中的OnClickListener。然后,在onItemClick()方法中,我们可以通过getItemAtPosition()方法获取点击的项并执行适当的操作。这样,当列表项由于Clickable视图的点击事件而被点击时,我们仍然可以处理此项的点击事件。