最近在学习android,对Android有些关键的知识点进行记录,以便后面的学习。
在创建的Activity如果继承自ListActivity类,则其默认拥有一个Listview控件提供使用, 下面主要就Listview中,item点击事件和长按事件的进行说明。
1、首先获得listview实例;
ListView lv = getListView();
2、添加点击事件
对lv添加点击监听器。
lv.setOnItemClickListener(new OnItemClickListener() { public void onItemClick(AdapterView<?> parent, View view, int position, long id) { // When clicked, show a toast with the TextView text TextView tv = (TextView)view.findViewById(R.id.textViewVideoTitle); Toast.makeText(getApplicationContext(), tv.getText(), Toast.LENGTH_SHORT).show(); } });
其中R.id.textViewVideoTitle 是Listview,item中的一个TextView控件。
3、添加长按事件
lv.setOnItemLongClickListener(new OnItemLongClickListener(){ @Override public boolean onItemLongClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) { // TODO Auto-generated method stub // When clicked, show a toast with the TextView text TextView tv = (TextView)arg1.findViewById(R.id.textViewVideoTitle); Toast.makeText(getApplicationContext(), tv.getText(), Toast.LENGTH_SHORT).show(); return false; } });
备注:
对于缺少的包,在eclipse中按Ctrl+shift+O就可以自动引入。