litterbugkid
litterbugkid

Reputation: 3666

Dynamically creating ImageButtons and adding them to layout with OnClickListeners

I'm trying to dynamically and programmatically create ImageButtons and add them to my Scrolling LinearLayout. I've been able to add them, but when I try to add onClickListeners to them, all their view ID's are -1; hence not being able to find out which button was clicked.

public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);


        OnClickListener imageClickListener;
        imageClickListener = new OnClickListener(){

            @Override
            public void onClick(View v) {
                System.out.println("id clicked: " + v.getId());             
            }
        };


        for (int i = 0; i<images.length; i++)
        {
            LinearLayout il = new LinearLayout(this);
            il.setOrientation(LinearLayout.HORIZONTAL);
            il.setMinimumHeight(LayoutParams.WRAP_CONTENT);
            il.setMinimumWidth(LayoutParams.WRAP_CONTENT);

            int imageid = 0;
            ImageButton ib;
            BitmapDrawable imagebd;
            imageid = getResources().getIdentifier("drawable/" + images[i], null, getPackageName());
            imagebd = resizeImage(imageid);
            ib = new ImageButton(this);


            ib.setClickable(true);
            ib.setOnClickListener(imageClickListener);
            ib.setImageDrawable(imagebd);
            ib.setMinimumHeight(size);
            ib.setMinimumWidth(size);       
            ib.setMaxHeight(size);
            ib.setMaxWidth(size);
            imageButtons.add(ib);
            il.addView(ib);
            System.out.println("id: " + ib.getId());

            ll.addView(il);
        }
        this.setContentView(sv);

    }

Upvotes: 0

Views: 6279

Answers (2)

Triode
Triode

Reputation: 11359

 ImageButton ib = new ImageButton(this);
 ib.setId(i);

Try this

Upvotes: 1

AlexMok
AlexMok

Reputation: 764

Why not call ib.setId(i) ? If you want an id, you have to define it when you create the image button!

Upvotes: 1

Related Questions