Fang Shuwei
Fang Shuwei

Reputation: 41

Android is there ClickListener for linearLayout using addView?

I'm trying to create pinterest like layout. I find a way to achieve this: Android heterogeneous gridview like pinterest?!

However the problem is: I want to view item details after clicking each picture. But as I am using LinearLayout.addView() to add all the ImageViews, I'm not sure how I can get it clickable?

Is there anyway to be able to click each item on the view?

Upvotes: 3

Views: 4166

Answers (4)

Buffalo
Buffalo

Reputation: 4052

Use:

imageView.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            //do magic
        }
    });

And in your layout file mark the ImageView as clickable:

<ImageView
...
android:clickable="true">
...
</ImageView>

Upvotes: 1

BurunduK
BurunduK

Reputation: 293

Use this :

view.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // ADD your action here

            }
        });

or make your class implement the OnClickListner Interface and override the onClick() method

Upvotes: 1

Raghav Sood
Raghav Sood

Reputation: 82563

Building on the code that you linked, you can add a listener to each image view as you create it:

linear1 = (LinearLayout) findViewById(R.id.linear1);
linear2 = (LinearLayout) findViewById(R.id.linear2);
linear3 = (LinearLayout) findViewById(R.id.linear3);

for(int i=0;i<n;i++)
{
   ImageView iv = new ImageView(this);
   iv.setImageResource(R.id.icon);
   iv.setOnClickListener(new OnClickListener() {
       public void onClick(View v) {
           //Your click code
       }
   }

   int j = count % 3;  <---- 
   if(j==0)
       linear1.addView(iv);
   else if(j==1)
       linear2.addView(iv);
   else
       linear3.addView(iv); 
}

Upvotes: 0

Michael Celey
Michael Celey

Reputation: 12745

You can do this pretty easily by adding tag information to your image view that can be displayed when clicked.

Adding your image view would look like:

ImageView iv = new ImageView(context);
iv.setOnClickListener(your_listener);
iv.setTag("Item information");
linearLayout.addView(iv);

Then in your click listener:

public void onClick(View v) {
    if(v instanceof ImageView) {
        String info = (String)v.getTag();
        /* Show information here */
    }
}

Upvotes: 1

Related Questions