سؤال

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

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top