有人能给我一个On item click侦听器的例子,用于带有基础适配器的列表视图吗?
我的列表视图包含两个文本视图和一个复选框。我想创建一个on item click侦听器,这样当按下一个项目(或行)时,它会勾选相应的行复选框。
我尝试过谷歌,但找不到任何关于它的例子
谢谢
答案 0 :(得分:7)
所以,适配器并不重要,但我相信你要做的事情非常简单,首先你需要得到ListView
的参考,我将其称为listView
设置适配器后,您可以使用setOnItemClickListener
创建点击操作
listView.setAdapter(adapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public boolean onItemClick(AdapterView<?> parent, View view, int position, long id) {
//here you can use the position to determine what checkbox to check
//this assumes that you have an array of your checkboxes as well. called checkbox
checkBox[position].setChecked(!checkBox.isChecked());
}
});
答案 1 :(得分:0)
实际上很简单,执行动作“setAdapter”后你必须这样做:
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(getApplicationContext(), "You click on position:"+position, Toast.LENGTH_SHORT).show();
}
});
答案 2 :(得分:0)
以下代码正常运行:
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent,
View view, int position, long id) {
Toast.makeText(getApplicationContext(),
"You click on position:"+position, Toast.LENGTH_SHORT).show();
}
});
但是当我点击items
时,它会进入其他活动。我该怎么办?
答案 3 :(得分:0)
您可以使用OnItemClick()方法的View参数访问listview行的所有元素。例如
listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent,
View view, int position, long id) {
// second parameter View view entire row object that is clicked - in your case
// two text views and the checkbox
// supposing your checkbox is set up with an id in the xml as idchkbox
// You can access it by findview by id and set it true or false;
android.widget.CheckBox chkbox = view.findViewbyId(R.id.idchkbox);
chkbox.setChecked = true;
return;
});