如何在onitemclick获取ListView的item

要想搞清楚这个问题,首先需要明确下onItemclick里的形参的意义

public void onItemClick(AdapterView<?> parent, View view, int position, long id) 
官方文档:

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.

一目了然:直接view.findViewId()...即可选择选中的子item里的控件

但是下边这方法如果listView里的item多的需要滚屏才能显示完全,则点击滚屏后出来的必报错空指针:

parent.getChildAt(position).findViewById(...)
实际上:

这个方法的取值范围在 >= ListView.getFirstVisiblePosition() &&  <= ListView.getLastVisiblePosition(); 
1)所以如果想获取前部的将会出现返回Null值空指针问题; 
2)getChildCount跟getCount获取的值将会不一样(数量多时); 
3 )如果使用了getChildAt(index).findViewById(...)设置值的话,滚动列表时值就会改变了。 
   需要使用getFirstVisiblePosition()获得第一个可见的位置,再用当前的position-它,再用getChildAt取值!即getChildAt(position - ListView。getFirstVisiblePosition()).findViewById(...)去设置值 

2.如果想更新某一行数据,需要配合ListView的滚动状态使用,一般不滚动时才加载更新数据 

//全局变量,用来记录ScrollView的滚动状态,1表示开始滚动,2表示正在滚动,0表示停止滚动  
伪代码 
ListView设置 
public int scrollStates; 
class OnScrollListenerImpl implements OnScrollListener{ 
@Override 
public void onScrollStateChanged(AbsListView view, int scrollState) { 
scrollStates = scrollState;  


@Override 
public void onScroll(AbsListView view, int firstVisibleItem, 
int visibleItemCount, int totalItemCount) { 
int lastInScreen = firstVisibleItem + visibleItemCount; 

listView.setOnScrollListener(new OnScrollListenerImpl()); 


Activity中 
if(scrollStates==OnScrollListener.SCROLL_STATE_IDLE){ 

更新视图数据 

猜你喜欢

转载自blog.csdn.net/qq_20089667/article/details/52588784