如何在ListView上收听点击事件?
这就是我现在拥有的
ListView list = (ListView)findViewById(R.id.ListView01); ... list.setAdapter(adapter);
当我做以下
list.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { public void onItemSelected(AdapterView parentView, View childView, int position, long id) { setDetail(position); } public void onNothingSelected(AdapterView parentView) { } });
这似乎没有点击任何事情.
所有这些代码都存在于扩展Activity的类中.
在列表视图中,使用 setOnItemClickListener
假设ListView对象是lv,请执行以下操作 -
lv.setClickable(true); lv.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView> arg0, View arg1, int position, long arg3) { Object o = lv.getItemAtPosition(position); /* write you handling code like... String st = "sdcard/"; File f = new File(st+o.toString()); // do whatever u want to do with 'f' File object */ } });
您需要在适配器类getView()方法中设置膨胀视图"可单击"和"能够侦听单击事件".
convertView = mInflater.inflate(R.layout.list_item_text, null); convertView.setClickable(true); convertView.setOnClickListener(myClickListener);
并在ListActivity中声明单击侦听器,如下所示,
public OnClickListener myClickListener = new OnClickListener() { public void onClick(View v) { //code to be written to handle the click event } };
仅当您通过扩展BaseAdapter自定义适配器时才适用.
有关详细信息,请参阅ANDROID_SDK/samples/ApiDemos/src/com/example/android/apis/view/List14.java
我之前的两个答案是正确的 - 你可以使用OnItemClickListener
.
这是很好的注意,之间的区别OnItemClickListener
和OnItemSelectedListener
,虽然听上去含蓄,其实显著,为项目选择和重点与您的触摸模式相关AdapterView
.
默认情况下,在触摸模式下,没有选择和焦点.您可以在这里查看有关该主题的更多信息.
这个解决方案非常简约,不会弄乱您的代码.
在你的list_item.xml(不是listView!)中分配属性android:onClick,如下所示:
然后在你的活动中调用这个方法:
public void onClickDoSomething(View view) { // the view is the line you have clicked on }
你必须用setOnItemClickListener
某人说.
代码应该是这样的:
listView.setOnItemClickListener(new OnItemClickListener() { public void onItemClick(AdapterView> parent, View view, int position, long id) { // When clicked, show a toast with the TextView text or do whatever you need. Toast.makeText(getApplicationContext(), ((TextView) view).getText(), Toast.LENGTH_SHORT).show(); } });
首先,该类必须实现click listenener:
implements OnItemClickListener
然后将侦听器设置为ListView
yourList.setOnItemclickListener(this);
最后,创建clic方法:
@Override public void onItemClick(AdapterView> parent, View view, int position, long id) { Toast.makeText(MainActivity.this, "You Clicked at " +countries[+ position], Toast.LENGTH_SHORT).show(); }
你可以在这里查看和下载代码