Android GridView Button Click Handler
Asked Answered
P

4

6

I have an Android GridView with an ImageView, TextView and two Button's. The Grid is appearing fine but I am finding it difficult to handle button events within GridView. I am new to Android.

Any help would be appreciated.

Thanks.

Pyotr answered 4/11, 2012 at 16:51 Comment(1)
you'll get responses of much better quality if you post your code to accompany this.Innings
B
12

If you want the Buttons (and anything else) to have unique click actions in your layout, you need to write a custom adapter and override getView():

public MyAdapter(Context context, List<T> objects) {
    ...
    inflater = (LayoutInflater) context.getSystemService(LAYOUT_INFLATER_SERVICE);
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    ViewHolder holder;
    if(convertView == null) {
        // Inflate and initialize your layout
        convertView = inflater.inflate(R.layout.grid_item, parent, false);
        holder = new ViewHolder();
        holder.btnOne = (Button) convertView.findViewById(R.id.btnOne);
        holder.btnOne.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                // Do something
            }
        });
        // etc, etc...
        convertView.setTag(holder);
    }
    else
        holder = (ViewHolder) convertView.getTag();

    // Do things that change for every grid item here, like
    holder.textOne.setText(getItem(position));          
    return convertView;
}


class ViewHolder {
    Button btnOne;
    TextView textOne;
}

This concept has been explained quite well in various Google Talks over the years, here is one.


Addition

I am trying to set text of the TextView inside GridView column upon clicking on the button inside GridView.

You should be able to access any View in the layout in an onClick() method by asking for the View's parent and then getting the ViewHolder:

public void onClick(View v) {
    ViewHolder holder = (ViewHolder) ((View) v.getParent()).getTag();
    // Do something with holder.textOne now
}

(This assumes that your layout does not have any nested ViewGroups, so adjust accordingly.)

Bittencourt answered 4/11, 2012 at 17:7 Comment(5)
Thanks for your answer. I am trying to set text of the TextView inside GridView column upon clicking on the button inside GridView. I am unable to get the reference of the TextView. I am adding getView code of my adapter.Pyotr
I added an example to reference any other layout in the ViewHolder from a child. Let me know if this helps.Bittencourt
Thanks Sam. That really helped! My GridView's OnItemClick event is not firing. Is it because of the buttons inside the GridView?Pyotr
Yes. An OnClickListener in one View consumes the event, preventing it from reaching any other Views... If you want to call both you could add mGridView.performClick() to your button's onClick() (obviously mGridView is a class variable that references your GridView).Bittencourt
Benefits of a ViewHolder object documented here: developer.android.com/training/improving-layouts/…Olnek
K
4

Either setting OnClick listener inside adapter and listen to the same click, as explained in the following blog

inside adapter

 holder.okay_button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            ((GridView)parent).performItemClick(v,position,0);

        }
    });
 holder.cancel_button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            ((GridView)parent).performItemClick(v,position,0);

        }
    });

IN the java file.

gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int        position, long id) {
           switch(view.getId)
        {
         case R.id.okay_button:
           //do your stuff
           break; 
         case R.id.cancel_button:
           //do your stuff 
            break;
            }
    });

Note:if you are using more than one child item click listener, use switch case to check which item is clicked inside SetOnItemClickListener.Because Using if else triggers all click listener you have in your adapter. if any good solution for this is there let me know. Thanks.

Kermis answered 25/9, 2015 at 9:9 Comment(1)
It's a great help ! And the blog you linked to is terrific, thanks.Unavoidable
G
1
 gridView = root.findViewById(R.id.gridview);
    CustomAdapter customAdapter = new CustomAdapter();
    gridView.setAdapter(customAdapter);
    gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) 
        {
            if(view.getId() == R.id.buyButton) {
                Intent intent = new Intent(getActivity(), OrderSummary.class);
                intent.putExtra("name", canWaterName[i]);
                intent.putExtra("price", canWaterPrice[i]);
                intent.putExtra("image", canWaterImage[i]);
                startActivity(intent);
            }
        }
    });

inside custom adapter which extends base adapter

 @Override
    public View getView(final int position, View convertView, final ViewGroup parent) {
        View view1 = getLayoutInflater().inflate(R.layout.row_data,null);
        //getting view in row_data
        final TextView name = view1.findViewById(R.id.canwaterName);
        final TextView price = view1.findViewById(R.id.canwaterPrice);
        final ImageView image = view1.findViewById(R.id.images);
        name.setText(canWaterName[position]);
        price.setText(canWaterPrice[position]);
        image.setImageResource(canWaterImage[position]);
        final Button buy = view1.findViewById(R.id.buyButton);
        buy.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ((GridView)parent).performItemClick(v,position,0);
            }
        });
        return view1;
    }
Glaucoma answered 2/2, 2020 at 17:5 Comment(0)
E
0

You must use onItemClickListener

 gridview.setOnItemClickListener(new OnItemClickListener() {
        public void onItemClick(AdapterView<?> parent, View v, int position, 
                long row) {
 }

Position should tell you about element clicked. But I think gridview have problems handle objects with clicklisteners (like buttons). Maybe would better changes gridview for other container. If you needs gridview you can use setOnTouchListener for catch position in screen and create a manual onitemclicklistener.

Eustashe answered 4/11, 2012 at 17:1 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.