以编程方式创建 ImageButton 时,它不会添加到视图中

When creating an ImageButton programmatically it is not added to view

我想以编程方式将 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);
}

如有任何建议,我们将不胜感激。

请注意您的 setContentView 方法。除此之外 答案可以让您找到答案。

一切看起来都很好,但您永远不会为添加的 ImageView 定义资源 ID。因此,您的语句 previewImg.getId() 将 return "NO_ID"

为新 ImageView 设置一个 ID,如下所示:

    previewImg.setId(View.generateViewId()); // API 17+

这将添加图像按钮,但您必须设置约束以满足您的需要。

而不是使用:previewImg.setImageBitmap(displayImage);

使用这个:previewImg.setImageResource(R.mipmap.ic_launcher);

public void addButtonImage () {
    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.setImageResource(R.mipmap.ic_launcher); // 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);
}

需要设置 ImageButton 的 LayoutParams

ConstraintLayout.LayoutParams lp = new ConstraintLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);

previewImg.setLayoutParams(lp);

您可能还需要设置边距和填充。