0


I want a custom listview in android studio that each item has a button. By clicking on this button it should return the id of the item in the listview that the button is in it to the main activity.
I had recently added the layout xmls and my only problem is in the MainActivity.java and the class that is needed in it.

Phantômaxx
  • 37,901
  • 21
  • 84
  • 115
  • What code have you already written to try and get your result? How is it not working yet? –  Jul 25 '17 at 21:51

1 Answers1

0

In the adapter's getView method set the button's tag e.g.:-

    public View getView(int position, View convertview, ViewGroup parent) {


        Button yourbutton = (Button) view.findViewById(R.id.yourbuttonid);
        yourbutton.setTag(position);
        .......

In the button's onClick handling use int position = (int) view.getTag(); to retrieve the position which should correlate to the array's index.

There are two main ways of handling the button's onClick in a ListView


1) specify the method to be used in the Button's XML (only since API level 4) and provide the handling method in the invoking activity:-

Example XML :-

<Button android:id="@+id/mybutton"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Click"
    android:onClick="myButtonClicked" />

Example handler in the activity that includes the respective ListView

    .....
    public myButtonClicked(View view) {
        int position = (int) view.getTag();
        ....
    }

2) Include setting the Listener and the onCLick handling in the ListView's adapter's getView method.

Example :-

        public View getView(int position, View convertview, ViewGroup parent) {

    
            Button yourbutton = (Button) view.findViewById(R.id.yourbuttonid);
            yourbutton.setTag(position);
            yourbutton.setOnClickListener(new OnClickListener() {
               public void onClick(View view) {
                   int position = view.getTag();
               }
            });

You may wish to have a look at these, which cover the above in more detail

I personally find the XML method very convenient. I utilise a Style as the basis for the buttons (I use a TextView for the buttons) so have a single method (as set in the Style) that I just incorporate into the respective activities. This even copes admirably with multiple Buttons per ListView item.

Community
  • 1
  • 1
MikeT
  • 51,415
  • 16
  • 49
  • 68