7ListView3

来源:互联网 发布:org.apache.kafka jar 编辑:程序博客网 时间:2024/05/07 03:04
下面我们来实现当listview中的某项被选中时如何添加响应函数:


这里我们需要知道在android中有这么一个类,他的名字叫做AdapterView,其实ListView是从这个类继承而来的
那么在这个类中,实现了一个接口,这个接口叫做OnItemClickListener,这是一个监听器,用来监听AdapterView中
的组件被选中这个事件,在这个接口中有一个方法,叫做 onItemClick,用来响应不同item被点击时所触发的事件。


开发者对于这个方法的说明如下:
public abstract void onItemClick (AdapterView<?> parent, View view, int position, long id)


Since: API Level 1
Callback method to be invoked when an item in this AdapterView has been clicked.
Implementers can call getItemAtPosition(position) if they need to access the data associated with the selected item.
Parameters


parent The AdapterView where the click happened.
view The view within the AdapterView that was clicked (this will be a view provided by the adapter)
position The position of the view in the adapter.
id The row id of the item that was clicked.


在这里我们可以根据position的值来确定哪个item被点击了,注意position是从0开始的。
id其实和position是一样的。


我们只需要对ListView对象进行setOnItemClickListener(),然后再在这个OnItemClickListener
的类定义中重载onItemClick()函数,便可以进行事件的响应


对于第一个参数,指的是这个adapter容器,我们可以使用getChildAt()函数来获得这个位置上的view。
以下代码通过上述方法实现了当item被选中时的背景色设置(注意不是点击时的背景色):


private int oldPosition = -1;
@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
if(oldPosition != -1){
   arg0.getChildAt(oldPosition).setBackgroundColor(Color.TRANSPARENT);
  }
  oldPosition = arg2;
  arg1.setBackgroundColor(Color.GRAY);
}

原创粉丝点击