user5155835
user5155835

Reputation: 4742

android: one click listener on many imageviews in layout

I have the following scenario:

enter image description here

In a layout, I have imageviews aligned horizontally and vertically as shown in image.

First, which layout should be used for this purpose? RelativeLayout or FrameLayout? ListView inside the layout?

Also, instead of writing setOnClickListener for every imageview, how can I write just one click listener to get the clicked imageview?

Upvotes: 1

Views: 155

Answers (3)

Satyen Udeshi
Satyen Udeshi

Reputation: 3243

Use 'GridView' in the layout and use 'setOnItemClickListener' to handle click events,

You can find more details in below link GridView.

Upvotes: 0

kevin4z
kevin4z

Reputation: 349

GridView can achieve the effect. I think you can look at this Grid View.

Upvotes: 0

nbokmans
nbokmans

Reputation: 5747

A GridView is perfect for this. For more information on GridView, look here.

As for your onClickListener question: there is no easy way to do this, but what you can do is something like this:

  1. Have an array containing every ImageView id like so:

    public static final int[] IMAGE_VIEWS = {R.id.imageView1, R.id.imageView2, R.id.imageView3 /*etc*/}; //Make sure to list from the first imageview to the last image view in correct order
    
  2. Define an onClickListener

    private View.OnClickListener imageViewListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            for (int i = 0; i < IMAGE_VIEWS.length; i++) {
                if (v.getId() == IMAGE_VIEWS[i]) {
                    doSomethingWithImageViewClick(i); //if ImageView 4 was clicked, variable 'i' will be 3 (because arrays start at index = 0).
                }
            }
        }
    }
    
  3. Set the onClickListeners for all your imageViews:

    final ImageView view1 = (ImageView) view.findViewById(R.id.imageView1);
    view1.setOnClickListener(imageViewListener);
    //etc
    

Upvotes: 2

Related Questions