java以编程方式创建ImageButton时,不会将其添加到视图中
我想以编程方式将ImageButton添加到特定的约束布局。也受特定指导方针约束的人。到目前为止,我已经实现了下面的方法,它没有给出任何错误,但是,除了debugText之外,似乎什么也没有发生
public void addButtonImage () {
setContentView(R.layout.activity_homepage); // - Moved out of method
ConstraintLayout conL = (ConstraintLayout)findViewById(R.id.newLayout);
ImageButton previewImg = new ImageButton(this);
Guideline leftGl = (Guideline)findViewById(R.id.leftGideLine);
Guideline rightGL = (Guideline)findViewById(R.id.rightGuideLine);
ImageView header = (ImageView) findViewById(R.id.Header);
previewImg.setImageBitmap(displayImage); // displayImage variable assigned out of method
previewImg.setBackgroundColor(Color.parseColor("#FFFF00"));
conL.addView(previewImg);
ConstraintSet conS = new ConstraintSet();
conS.clone(conL);
conS.constrainHeight(pp.getId(), 90);
conS.constrainWidth(pp.getId(), 0);
conS.connect(previewImg.getId(), ConstraintSet.TOP, header.getId(), ConstraintSet.BOTTOM);
conS.connect(previewImg.getId(), ConstraintSet.LEFT, leftGl.getId(), ConstraintSet.RIGHT);
conS.connect(previewImg.getId(), ConstraintSet.RIGHT, rightGL.getId(), ConstraintSet.LEFT);
conS.applyTo(conL);
}
任何建议都将不胜感激
# 1 楼答案
需要设置ImageButton的LayoutParams:
此外,您可能需要设置边距和填充
# 2 楼答案
小心你的setContentView方法。除此之外this答案可以帮助你找到答案
# 3 楼答案
这将添加图像按钮,但您必须设置约束以满足您的需要
而不是使用:
previewImg.setImageBitmap(displayImage);
使用这个:
previewImg.setImageResource(R.mipmap.ic_launcher);
# 4 楼答案
看起来一切正常,但您从未为添加的
ImageView
定义资源id。因此,您的语句previewImg.getId()
将返回“NO_ID”为新的
ImageView
设置一个id,如下所示: