I\'m facing some difficults when I try to use the performItemClick funcion of the ListView.
All I want to do is to perform a click programatically i
just should use performItemClick()
and it's okay.
listView.performItemClick(listView.getAdapter().getView(listView.getSelectedItemId, null, null), listView.getSelectedItemId, listView.getAdapter().getItemId(listView.getSelectedItemId));
I tried the code below and it worked.
getListView().performItemClick(null, 0, getListAdapter().getItemId(0));
The first parameter (view) can be null.
I just meet this freak problem today , and I try me best to deal with it. My condition is , when I first init the layout , I need make some item checked. But when I use gridView.getChildAt(position) , always return null. I met this problem before , caused by Not finishing drawing layout . So I send a post message . handler.postDelayed( .. , ..) , It works. Thanks who motion this Exception.
This works best for me. Run this on the main thread.
new Handler().post(new Runnable() {
@Override
public void run() {
mList.performItemClick(
mList.getChildAt(mActivePosition),
mActivePosition,
mList.getAdapter().getItemId(mActivePosition));
}
});
This is similar to Arun Jose's answer, but it will queue a message to the main thread to give the ListView
some time to initiate.
At Firstly I tried to use this code in my Fragment(Master/Detail -> NameListFragment)
getListView().performItemClick(null, 0, getListView().getAdapter().getItemId(0));
But it didn't work. When I did @Override onStart()
method in fragment and I moved my code to onStart()
. After that it works properly for me.
This work for me If you would get weird result when using getView, this is because the list item you want does not exist within visible parts. Use below:
private View getViewFromAdapterByPosition(int position, ListView listView)
{
View view;
int firstVisiblePos = listView.getFirstVisiblePosition();
int lastVisiblePos = listView.getLastVisiblePosition();
if (position < firstVisiblePos || position > lastVisiblePos) {
view = listView.getAdapter().getView(position, null, listView);
} else {
view = listView.getChildAt(position - firstVisiblePos);
}
return view;
}
And then,
listView.performItemClick(getViewFromAdapterByPosition(index, listView), index, 0);