Android ListView的事件监听
1、数据项点击事件,针对的是ListView每个数据项的点击事件
listView.setOnItemClickListener { _, _, position, _ ->
Toast.makeText(this, "position: $position", Toast.LENGTH_LONG).show()
}
2、ListView组件焦点事件(不是指单个item,是整个ListView)
listView.setOnFocusChangeListener { _, hasFocus ->
if (hasFocus) {
Log.d("MainActivity", "has focus ... ")
} else {
Log.d("MainActivity", "lose focus ...")
}
}
3、ListView中数据项被选中事件监听
bind.listView.onItemSelectedListener = object: AdapterView.OnItemSelectedListener{
override fun onItemSelected(parent: AdapterView<*>?,view: View?,position: Int,id: Long) {
Log.d("MainActivity", "position: $position")
}
override fun onNothingSelected(parent: AdapterView<*>?) {
Log.d("MainActivity", "onNothingSelected ...")
}
}
AdapterView.OnItemSelectedListener中有两个方法,onItemSelected在数据项被选中时触发,onNothingSelected在LiveView没有任何数据项被选中时触发。
4、监听ListView中item焦点的变化
假设有一个需求,item获取焦点背景颜色为blue,没有焦点的背景颜色为white,则伪代码如下:
Adapter中代码
class FruitAdapter(activity: Activity, private val resourceId: Int, data: List<Fruit>): ArrayAdapter<Fruit>(activity, resourceId, data) { var position: Int = 0 override fun getView(position: Int, convertView: View?, parent: ViewGroup): View { Log.d("FruitAdapter", "position: $position convertView: $convertView") val view = ... //加载布局伪代码 if (this.position == position) { view.setBackgroundColor(Color.BLUE) } else { view.setBackgroundColor(Color.WHITE) } return view } }
Adapter中定义了一个position,用来记录当前哪个item被选中,数值由Activity那边监听更新
MainActivity中代码
override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) val bind = ActivityMainBinding.inflate(layoutInflater) setContentView(bind.root) val fruitAdapter = FruitAdapter(this, R.layout.fruit_item, fruitList) bind.listView.adapter = fruitAdapter bind.listView.onItemSelectedListener = object: AdapterView.OnItemSelectedListener{ override fun onItemSelected(parent: AdapterView<*>?,view: View?,position: Int,id: Long) { Log.d("MainActivity", "position: $position") fruitAdapter.position = position fruitAdapter.notifyDataSetChanged() } override fun onNothingSelected(parent: AdapterView<*>?) { Log.d("MainActivity", "onNothingSelected ...") } } }
看红色代码即可,获取ListView对象后,添加onItemSelectedListener 监听,然后把选中的item下标传递给Adapter。这时调用Adapter的方法notifyDataSetChanged()来通知Adapter刷新数据,再次执行Adapter中getView()方法,在getView方法中对下标进行了比较,相等下标的view背景色变为blue,否则变为while,这样就实现了ListView中item焦点变化事件的监听。
posted on 2023-06-28 19:59 Devil'soul 阅读(348) 评论(0) 编辑 收藏 举报