Click Button in ListView And Get Item Position

On September 5, 2014, in Android, by James Liu

In my android app “Memo English Fruit Master”, I create a customized ListView. In each ListView item, I put a button inside so when user clicks on the button, the app will play a voice over according to the text in that ListView item. The problem is here, how do I know which voice over the app should play. Hence, I need to know the position of the item in ListView. Here are several ways to get listview item position on click.

Set onListItemClick Event Listener on ListView

This is the most simple way to get position of an item within a ListView. In most of the case, users click on an item with a ListView, this event will be triggered and it will call onListItemClick listener by passing four parameters:

  • The ListView where the click happened
  • The view that was clicked within the ListView
  • The position of the view in the list
  • The row id of the item that was clicked

First, we set the listener on the listview.

listView.setOnItemClickListener(onItemClickListener);

Then, we define the listener. Here is the example source code:

private OnItemClickListener onItemClickListener = new OnItemClickListener() {

	@Override
	public void onItemClick(AdapterView<?> arg0, View arg1, int position,
			long arg3) {
		// TODO Auto-generated method stub
		//do your job here, position is the item position in ListView
	}
};

Get ListView Item Position by getPositionForView

The first solution is suitable for user clicking on the ListView item. How about user clicks a button within the ListView item? Let’s say we set the click listener on a button in the getView function which is defined in adapter class.

mybutton.setOnClickListener(myButtonClickListener);

Then we define the onclick listener:

private OnClickListener myButtonClickListener = new OnClickListener() {
	@Override
	public void onClick(View v) {
		View parentRow = (View) v.getParent();
		ListView listView = (ListView) parentRow.getParent();
		final int position = listView.getPositionForView(parentRow);
	}
};

Store Position Data on Button By setTag

Here is another simple way to find the position of item by button click. In the getView function, we can use setTag to set the current view position as tag on the button. In the button click listener, we get the tag of the button and convert it as integer position value.

Here is how we set the tag in getView function:

mybutton.setTag(position);
mybutton.setOnClickListener(myButtonClickListener);

In the button click listener, we will get the tag and find the position value. Here is the source code:

private OnClickListener voiceButtonClickListener = new OnClickListener() {
	@Override
	public void onClick(View v) {
		int position = (Integer) v.getTag();
	}
};
 

43 Responses to “Click Button in ListView And Get Item Position”

  1. Yazdan says:

    thanks , it was really useful for me!

  2. sham says:

    thnks…Very helpful

  3. Dhwani says:

    Thank you so much! Great help..

  4. shenba says:

    I want to access the listview from one class to another class.my listview is in fragment.And I have the delete button for listitems in adapter class.How can I get that???

    • James says:

      If you can listen the button click and get the row index in the listener, it doesn’t matter where you want to access the listview.

  5. vahid says:

    Thank you man , I’ve confused for day’s until saw this good tutorial

  6. prashant says:

    how to get image and text from listview
    and also set it in textview…

  7. Polly says:

    This washed away away code sweat…I was using a popup menu on a listview but it was returning the current position as null.

    Thanks again

  8. hussein says:

    this is really great and usefull, thanks alot

  9. shruti says:

    what is this getview and how to write set code of button there

  10. Rajendra dubey says:

    Thank you very much brother, you saved my day.
    Thanks a lot. It was really very helpful.

  11. Hemant Sharma says:

    Really very simple and easy.
    Keep it up, Thanks.

  12. yadhu says:

    Thank you very much.Helped me lot

  13. Vikesh says:

    What if i want to change the background of the button which was clicked and whose position we just found out !

  14. shalini says:

    hi i tried the same but im getting this error android.widget.listview cannot be cast to android.widget.LinearLayout any hope how to solve t

    • James Liu says:

      Hello, I think the error message tells you the problem very clear. You cannot assign ListView object to LinearLayout reference. Please read my code carefully and you will find the solution.

      Best Regards
      James

  15. pradeep says:

    Good tutorial

    thank you dude

  16. Stefano says:

    Thanks! The second solution was useful for me.

  17. Neha dubey says:

    i have custom listview with textview and imageview and one button which name is ADD. i want to access list item’s data on other activity on ADD button click. how can get only perticuler list item’s values??

    • James Liu says:

      First, you need to get your list item’s data when you click on the ADD button. After you get the data, you can pass the data to your new activity.

  18. André says:

    The second solution worked wonders for me, thanks a lot!

  19. chithra says:

    thank u very much…sir..its very helpful for me…i have anothr doubt..
    i want to view details from webservices..the details wll come within listview..

  20. Eka Cahya says:

    Thanks dude, work like a charm.
    you save my day 🙂

  21. Maulik says:

    I am making a To-Do app. I am using SQLite to store the data from editText View.
    I want to get the id as the position.
    I tried the above code but it throws the nullPointerException to the delete Button.

  22. Jey says:

    sorry, if I want to put a ButtonDownload into a listView to start download the file from getLink, for example, how can I call this?

    Thankyou for any helps

    • James Liu says:

      Then, you just put a download button in the listView. Once you click the button, you will get the index of the row, and start to download the corresponding file.

      • Jey says:

        I tried but It return me error.
        here is my button buttonDownload in my Adapter.class:

        viewHolder.btnDetails = (Button) row.findViewById(R.id.btnDetails);
        viewHolder.btnDetails.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
        View parent = (View)v.getParent();
        ListView listView = (ListView) parent.getParent();
        final int pos = listView.getPositionForView(parent);
        if(frameLayout.getVisibility()==View.GONE){
        showFrameLayout();
        } else {
        hideFrameLayout();
        }

        }
        });

        and out of create the following….

        public class ViewHolder{
        Button btnDownload;
        Button btnDetails;
        }

        private void showFrameLayout(){
        frameLayout = (FrameLayout) frameLayout.findViewById(R.id.frame_layout_listview);
        frameLayout.setVisibility(View.VISIBLE);
        }
        private void hideFrameLayout(){
        frameLayout = (FrameLayout) frameLayout.findViewById(R.id.frame_layout_listview);
        frameLayout.setVisibility(View.GONE);
        }
        but when I push the button it goes to open another cell into a listView. can you tell me where is my mistake?

        • Jey says:

          sorry I wrote a mistake. the Button is button=btnDetails
          and It should open a FrameLayout of each issue. but when I select button one it opes issue 3.
          I think there is something wrong in getPosition.

        • James Liu says:

          Do you get the position by this:

          final int pos = listView.getPositionForView(parent);

          • Jey says:

            this is from the Adapter.class
            @Override
            public View getView(final int pos, final View convertView, final ViewGroup parent){
            RelativeLayout row = (RelativeLayout)convertView;
            Log.i(“AtlantisSites”, “getView pos = ” + pos);
            //ViewHolder mainViewHolder = null;
            if(null == row){

            this is how I get position

          • James Liu says:

            If you can get the pos, then my code doesn’t have any problem.

  23. nttu says:

    SetTag is great solution. Thank you!

  24. Direndra says:

    Last one worked for me.. Thanks.

Leave a Reply

Free WordPress Themes

WordPress Themes