7ListView3

下面我们来实现当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);
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值