I create the below code:
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);
}
}
}
});
I want to realize a function like when i click one item of Listview
, it will show a view, and the other items of Listview will be hidden. But mListView.getChildAt(i)
will have the null pointer after exceed mListView.getChildCount()
.
How to solve this? Thanks in advance!
AdapterView.getCount() returns the number of data items, which may be larger than the number of visible views, that's why you are getting null pointer exception, because you are trying to find views which do not exist in the current visible ListView items.
To solve this issue you will first need to find the first visible item in the ListView using getFirstVisiblePosition()
and the last visible item using getLastVisiblePosition()
. Change the for loop condition as:
int num_of_visible_view=mListView.getLastVisiblePosition() -
mListView.getFirstVisiblePosition();
for (int i = 0; i < num_of_visible_view; i++) {
// do your code here
}
you can not implement this in onItemClick.
As you can access only visible child not all child.
What you can do is on onItemClick
you can send the position in adapter
and then set the logic there in getView too change view
and update the adapter in listview, or notify for changes.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With