mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View v, int position,
long id) {
for (int i = 0; i < mListView.getCount(); i++) {
View callLogView = mListView.getChildAt(i);
mRelativeLayout = (LinearLayout)callLogView.findViewById(R.id.myShow);
if(i == position){
if(mRelativeLayout.getVisibility() == View.GONE){
mRelativeLayout.setVisibility(View.VISIBLE);
}
else{
mRelativeLayout.setVisibility(View.GONE);
}
}else{
mRelativeLayout.setVisibility(View.GONE);
}
}
}
});
如题,代码以附上,我现在想做的事是在点击一项ListView后显示出一个布局,而其它项的ListView隐藏,但在超过 mListView.getChildCount()后会出现空指针,求解!
没人知道么?mListView.getChildAt(i)在超过 mListView.getChildCount()后会出现空指针怎么解决??
看来,没有一个十全十美的办法,我采用一个实用的方法,使用mListView.getChildCount()循环,然后再写个滑动监听事件,滑动时再隐藏控件。
int wantedPosition = 10; // Whatever position you're looking for
int firstPosition = listView.getFirstVisiblePosition() - listView.getHeaderViewsCount(); // This is the same as child #0
int wantedChild = wantedPosition - firstPosition;
// Say, first visible position is 8, you want position 10, wantedChild will now be 2
// So that means your view is child #2 in the ViewGroup:
if (wantedChild < 0 || wantedChild >= listView.getChildCount()) {
Log.w(TAG, "Unable to get view for desired position, because it's not being displayed on screen.");
return;
}
// Could also check if wantedPosition is between listView.getFirstVisiblePosition() and listView.getLastVisiblePosition() instead.
View wantedView = listView.getChildAt(wantedChild);
你没有遍历列表视图的子类,这可能会影响性能。
你不能在 onItemClick 中实现。
因为你只能访问可见性的子类,不是所有的子类。
在 onItemClick 你可以在 adapter 中发送位置,然后在 getView 中设置逻辑改变 view, 并且更新 listview 中的 adapter。
AdapterView.getCount()返回的是数据项的数量,这可能比可见视图要多。因为你想在当前的 ListView 项中找根本就不存在的 Views ,就会获得空指针异常。
为解决这个问题,你需要使用getFirstVisiblePosition()
首先找到 Listview 中的第一个可见项,使用getLastVisiblePosition()
找到最后一个可见项。
使用下面的循环语句:
int num_of_visible_view=mListView.getLastVisiblePosition() -
mListView.getFirstVisiblePosition();
for (int i = 0; i < num_of_visible_view; i++) {
// do your code here
}
在adapter中的getview方法里操作每个view
View v = listView.getAdapter().getView(arg2,null,listView);
TextView t = (TextView) v.findViewById(R.id.textview);