Android - ListView - performItemClick

梦想与她 提交于 2019-11-26 12:25:17

问题


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 in the first item of the list.

How can I do that? I looked up that function in the documentation, but I didn\'t really understand its parameters.

I tried something like:

 myListView.performItemClick(myListView.getChildAt(0), 0, myListView.getChildAt(0).getId());

But it didn\'t work (myListView.getChildAt(0) returns null)

Thank you in advance!


回答1:


mList.performItemClick(
        mList.getAdapter().getView(mActivePosition, null, null),
        mActivePosition,
        mList.getAdapter().getItemId(mActivePosition));

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




回答2:


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



回答3:


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.




回答4:


I tried the code below and it worked.

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

The first parameter (view) can be null.




回答5:


I went with

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



回答6:


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.




回答7:


mList.performItemClick(
    mList.getChildAt(mActivePosition),
    mActivePosition,
    mList.getAdapter().getItemId(mActivePosition));

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




回答8:


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




回答9:


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.




回答10:


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.




回答11:


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.




回答12:


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



回答13:


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.




回答14:


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;
    }



回答15:


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




回答16:


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




回答17:


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  



回答18:


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



回答19:


This works for me:

listview.getSelectedView().performClick();



回答20:


This worked for me:

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



回答21:


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();
    }
}

}



来源:https://stackoverflow.com/questions/8094268/android-listview-performitemclick

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