45

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!

Jeff Mercado
  • 129,526
  • 32
  • 251
  • 272

24 Answers24

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

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

sulai
  • 5,204
  • 2
  • 29
  • 44
Arun Jose
  • 1,857
  • 1
  • 15
  • 24
29

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);
Steven
  • 3,200
  • 1
  • 17
  • 16
  • 2
    Shouldn't the last argument in performItemClick be listView.getAdapter().getItemId(position)? – raydowe Nov 08 '12 at 22:54
16

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.

sulai
  • 5,204
  • 2
  • 29
  • 44
  • I will use your answer in another answer as comments don't format code :/. Thanks for the handler – denispyr Jun 26 '13 at 21:19
  • 1
    I don't know why but after orientation change this method does not work – Jongz Puangput Jun 10 '14 at 13:53
  • @JongzPuangput One possible cause: your `ListView` has been re-created and you need to get a new reference for it after orientation change: `mList = getView().findViewById(R.id.list);` – sulai Feb 20 '15 at 10:05
  • its woring for me.. I did use BaseAdapter.. Thankx – Amitabha Biswas Jun 21 '15 at 12:43
  • 2
    This will not always work, since ViewGroup#getChildAt(int index) will work only on the currently visible items on screen, use getView(position, null, null) instead! – Maxim Rahlis Jul 14 '15 at 12:24
5

I tried the code below and it worked.

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

The first parameter (view) can be null.

Blehi
  • 1,990
  • 1
  • 18
  • 20
4

I went with

listView.getAdapter().getView(position, null, null).performClick();
koljaTM
  • 10,064
  • 2
  • 40
  • 42
2

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.

Pang
  • 9,564
  • 146
  • 81
  • 122
User Learning
  • 3,165
  • 5
  • 30
  • 51
1

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.

ralphgabb
  • 10,298
  • 3
  • 47
  • 56
1
mList.performItemClick(
    mList.getChildAt(mActivePosition),
    mActivePosition,
    mList.getAdapter().getItemId(mActivePosition));

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

Benoit Esnard
  • 2,017
  • 2
  • 24
  • 32
nick9999
  • 37
  • 3
0

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

denispyr
  • 1,403
  • 3
  • 21
  • 34
0

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.

Bob
  • 1,351
  • 11
  • 28
0

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.

Community
  • 1
  • 1
dinhokz
  • 895
  • 15
  • 36
0

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.

innershows
  • 64
  • 5
0

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

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;
    }
Maxime Claude
  • 965
  • 12
  • 27
0

myListView.getChildAt(0) returns null because used this very soon.

use a delay for it.

or use below code:

private class MyAdapter extends BaseAdapter
{
private final Context context;
private HashMap<Integer, View> views;

public MyAdapter(Context context)
{
    this.context = context;
    views = new HashMap<>();
}

@Override
public View getView(int position, View convertView, ViewGroup parent)
{
    if(convertView == null)
    {
        if(views.get(position) == null)
        {
            final LayoutInflater layoutInflater = LayoutInflater.from(context);
            convertView = layoutInflater.inflate(R.layout.my_grid, null, false);

            views.put(position, convertView);
        }
        else
            convertView = views.get(position);
    }

    TextView tv = convertView.findViewById(R.id.langView);
    tv.setText(languageList.get(position));

    return convertView;
}
}

and

adapter = new MyAdapter(getActivity());
myListView.setAdapter(adapter);

Runnable r = new Runnable()
{
    @Override
    public void run()
    {
        myListView.performItemClick(adapter.getView(position, null, myListView), position, 0);
    }
};

myListView.postDelayed(r, 100);
Ali Bagheri
  • 3,068
  • 27
  • 28
0

just should use performItemClick() and it's okay.

listView.performItemClick(listView.getAdapter().getView(listView.getSelectedItemId, null, null), listView.getSelectedItemId, listView.getAdapter().getItemId(listView.getSelectedItemId));
H.Fa8
  • 318
  • 3
  • 10
0

In my case, none of the options solved my problem, so I made an adaptation in my CursorAdapter class. I defined a global variable in the scope, so I just call the class changing this value and check the cursor position by passing the position value

 mProductsAdapter.currentPosition = requiredPosition

in my ProductsAdapter builder

  var currentPosition = 0

in bindView I do the check

 if (cursor.position == currentPosition) {
// perform action
}
AllanRibas
  • 678
  • 5
  • 14
-1

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

AlikElzin-kilaka
  • 34,335
  • 35
  • 194
  • 277
-1

This worked for me:

listView.getAdapter().getView(1, null, null).performClick();
Pang
  • 9,564
  • 146
  • 81
  • 122
-1

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  
Community
  • 1
  • 1
HourGlass
  • 1,805
  • 1
  • 15
  • 29
-1

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);
kenju
  • 5,866
  • 1
  • 41
  • 41
-1

This works for me:

listview.getSelectedView().performClick();
Pang
  • 9,564
  • 146
  • 81
  • 122
hamidjahandideh
  • 177
  • 2
  • 9
-1

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

  • It is being filled. At least it is not null. I have tried put that piece of code even after the adpter has been set but it still didn't work. This is driving me crazy! Any ideas? –  Nov 16 '11 at 20:38
-5

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

}

  • 1
    Thanks for replying, but this is not what I want. I want to perform a click PROGRAMATICALLY in my ListView using the method performItemClick. –  Nov 11 '11 at 13:38
  • Please remove this answer, it is incorrect! Thanks. – Anh Duy May 03 '17 at 03:59