Android 针对ListActivity中ListView 点击事件和长按事件

来源:互联网 发布:淘宝网小狗用品 编辑:程序博客网 时间:2024/05/16 19:35

最近在学习android,对Android有些关键的知识点进行记录,以便后面的学习。

在创建的Activity如果继承自ListActivity类,则其默认拥有一个Listview控件提供使用, 下面主要就Listview中,item点击事件和长按事件的进行说明。

1、首先获得listview实例;

[java] view plaincopyprint?
  1. ListView lv = getListView();  

2、添加点击事件

  对lv添加点击监听器。

[java] view plaincopyprint?
  1. lv.setOnItemClickListener(new OnItemClickListener() {  
  2.             public void onItemClick(AdapterView<?> parent, View view,  
  3.                     int position, long id) {  
  4.                 // When clicked, show a toast with the TextView text  
  5.                 TextView tv = (TextView)view.findViewById(R.id.textViewVideoTitle);  
  6.                 Toast.makeText(getApplicationContext(),  
  7.                         tv.getText(), Toast.LENGTH_SHORT).show();  
  8.             }  
  9.         });  
其中R.id.textViewVideoTitle 是Listview,item中的一个TextView控件。
3、添加长按事件

[java] view plaincopyprint?
  1. lv.setOnItemLongClickListener(new OnItemLongClickListener(){  
  2.             @Override  
  3.             public boolean onItemLongClick(AdapterView<?> arg0, View arg1,  
  4.                     int arg2, long arg3) {  
  5.                 // TODO Auto-generated method stub  
  6.                 // When clicked, show a toast with the TextView text  
  7.                 TextView tv = (TextView)arg1.findViewById(R.id.textViewVideoTitle);  
  8.                 Toast.makeText(getApplicationContext(),  
  9.                         tv.getText(), Toast.LENGTH_SHORT).show();  
  10.                 return false;  
  11.             }  
  12.         });  

备注:

对于缺少的包,在eclipse中按Ctrl+shift+O就可以自动引入。

0 0
原创粉丝点击