简体   繁体   中英

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);

    }

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

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

Try this

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM