Android - ListView - performItemClick

喜夏-厌秋 提交于 2019-11-27 00:56:08
Arun Jose
mList.performItemClick(
        mList.getAdapter().getView(mActivePosition, null, null),
        mActivePosition,
        mList.getAdapter().getItemId(mActivePosition));

Where mActivePosition is your click position! All the best! :)

This worked for me.

listView.performItemClick(
    listView.getAdapter().getView(position, null, null), position, position);

use the adapter to get the view for the position of the item. The other 2 parameters I didn't want so I left them null. Leaving convertView null causes the adapter to render a new view. It's a performance issue but since this is only happening once in a while it wont have much effect. I don't need to specify the parent for anything because I'm not using it.

position is just the spot where your item is located. Additionally these 2 lines of code before your performItemClick create the illusion of having the list item selected. They also ensure the appropriate item is on the screen.

listView.requestFocusFromTouch();
listView.setSelection(position);

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.

I tried the code below and it worked.

getListView().performItemClick(null, 0, getListAdapter().getItemId(0));

The first parameter (view) can be null.

I went with

listView.getAdapter().getView(position, null, null).performClick();
nick9999
mList.performItemClick(
    mList.getChildAt(mActivePosition),
    mActivePosition,
    mList.getAdapter().getItemId(mActivePosition));

where mActivePosition is the position of the child view in List View.

Using the code @sulal proposed, you may place it in onLoadFinished, if you use a LoaderManager. Eg something like

@Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
    //....
    // mSelectedId keeps the currently selected id
    // INVID is an invalid value
    if (mSelectedId == INVID) { // nothing selected
        // sulal's code
        new Handler().post(new Runnable() {
            @Override
            public void run() {
                mList.performItemClick(
                        mList.getChildAt(mActivePosition),
                        mActivePosition,
                        mList.getAdapter().getItemId(mActivePosition));
                mSelectedId = mList.getAdapter().getItemId(mActivePosition);
            }
        });            
    }

mActivePosition may be 0 (ie position on the first item) or a position kept during eg onPause

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.

i was working with performItemClick and it worked for me but with a little problem. i tried to color the background of the pressed item but it never worked, just notice that if you pass convert view as null (the second parameter) and then trying to do something on OnClick() it will not efect beacuse the getView() method of the Adapter give you a diffrent View Object. you need to manipulate the getView() method of your adapter to catch the View so you can qork on it.

dinhokz

If you are working on a unit test case. Try to use getInstrumentation().waitForIdleSync(), to wait the list be loaded, and extend the ActivityInstrumentationTestCase2 See this answer.

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 may be old but this may help :

lvList.performItemClick(null, index, lvList.getItemIdAtPosition(index) ); 

NOTE : the first param is null and will still work, if you have a custom adapter, convertView will be filled with custom layout and view and such.

-cheers / happy codings.

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);
User Learning

When using Listview (simple array adapter or custom adapter) define listview and other finally make perform click.

For example:

 //At onCreate function:

lv = (ListView) findViewById(R.id.listView);
        lv.setAdapter(new CustomAdapter(List_item.this, list, images));


lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id)    {
// on click function works
    }
}


int position = 0;
lv.performItemClick(lv.getAdapter().getView(position, null, null), position, lv.getAdapter().getItemId(position));

Note: After creating the setOnItemClickListener only you should call perform click. Otherwise, it will not correctly.

Try this one:

public static boolean performClicKOnLisViewFromIndex(ListView listView, int index){
        if(listView != null){
            if(listView.getAdapter()!= null && listView.getAdapter().getCount() >0 && listView.getAdapter().getCount() > index ){
                listView.performItemClick(
                        listView.getAdapter().getView(index, null, null),
                        index, listView.getItemIdAtPosition(index));
                return true;
            }
        }
        return  false;
    }

The performClick is probably called before listview was filled, put breakpoint in getView and on performItemClick and check wich is called first

getListView().performItemClick(null, 0, 0) did the trick for me (for position 0).

Dropping Some Experience.

using listview1.performItemClick, will also trigger your listview1.OnItemClickListener if you are using the listener with same listview in your code.

Hope It helps  

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);
hamidjahandideh

This works for me:

listview.getSelectedView().performClick();
Drilon Kastrati

This worked for me:

listView.getAdapter().getView(1, null, null).performClick();

This is from Begining Android Games. It creates a simple list of items which you can click to open a new activity. Each list item of course, would have to also be added to the AndroidManifest.xml as a separate activity with a .ListItem# name.

public class MainActivity extends ListActivity {
String tests[] = { "ListItem1",
                   "ListItem2",
                   "ListItem3",
                   "ListItem4"};

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setListAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, tests));
}

@Override
protected void onListItemClick(ListView list, View view, int position, long id) {
    super.onListItemClick(list, view, position, id);
    String testName = tests[position];

    try {
        Class<?> classInstance = Class.forName("your.package.name." + testName);
        Intent intent = new Intent(this, classInstance);
        startActivity(intent);
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    }
}

}

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!