[英]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. 我正在尝试以动态和编程方式创建ImageButtons并将它们添加到我的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; 我已经能够添加它们,但是当我尝试向它们添加
onClickListeners
,它们的所有视图ID都是-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)
? 为什么不拨打
ib.setId(i)
? If you want an id, you have to define it when you create the image button! 如果你想要一个id,你必须在创建图像按钮时定义它!
ImageButton ib = new ImageButton(this);
ib.setId(i);
Try this 尝试这个
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.