在ConstraintLayout中看不到我以编程方式添加的textviews

时间:2018-07-03 06:38:30

标签: android android-constraintlayout

我在ConstrainLayout中的代码中添加了2个textview,但是我看不到它们。 屏幕为空。 请有人帮我弄清楚这个吗? 非常感谢!

// suppose $response is the value you `var_dump`ed in a question.
echo $response->payment_url;   // same for other properties: $response->status

}

3 个答案:

答案 0 :(得分:2)

首先,ID应该不同,其次,您需要为TextView的宽度/高度添加约束:

    set.connect(tv1.getId(), ConstraintSet.LEFT, R.id.parent_Constraint, ConstraintSet.LEFT, 0);
    set.constrainWidth(tv1.getId(), WRAP_CONTENT);
    set.constrainHeight(tv1.getId(), WRAP_CONTENT);
    set.connect(tv3.getId(), ConstraintSet.RIGHT, R.id.parent_Constraint, ConstraintSet.RIGHT, 0);
    set.constrainWidth(tv3.getId(), WRAP_CONTENT);
    set.constrainHeight(tv3.getId(), WRAP_CONTENT);
    set.applyTo(mConstraintLayout);

为了避免冲突,可以使用资源xml定义ID。

  1. 在res \ values文件夹中创建ids.xml

  2. 定义ID:

    <resources>
        <item type="id" name="textView1" />
    </resources>
    
  3. 使用定义的ID:

    R.id.textView1
    

答案 1 :(得分:0)

你好,请遵循以下代码

        ConstraintLayout layout = (ConstraintLayout) findViewById(R.id.mainConstraint);
    ConstraintSet set = new ConstraintSet();

    ImageView view = new ImageView(this);
    layout.addView(view, 0);
    set.clone(layout);
    set.connect(view.getId(), ConstraintSet.TOP, layout.getId(), ConstraintSet.TOP, 60);
    set.applyTo(layout);

答案 2 :(得分:0)

TextView contactUs = new TextView(this);
contactUs.setText(R.string.contactus);
contactUs.setTextSize(25);
contactUs.setId(R.id.contactUs);

ConstraintLayout.LayoutParams clpcontactUs = new ConstraintLayout.LayoutParams(
    ConstraintLayout.LayoutParams.WRAP_CONTENT, ConstraintLayout.LayoutParams.WRAP_CONTENT);
contactUs.setLayoutParams(clpcontactUs);

constraintLayout.addView(contactUs);

ConstraintSet set = new ConstraintSet();
set.clone(mConstraintLayout);

set.connect(tv1.getId(), ConstraintSet.LEFT, R.id.parent_Constraint, ConstraintSet.LEFT, 0);
set.connect(tv3.getId(), ConstraintSet.RIGHT, R.id.parent_Constraint, ConstraintSet.RIGHT, 0);
set.applyTo(mConstraintLayout);

尝试这样的事情。

参考http://www.zoftino.com/adding-views-&-constraints-to-android-constraint-layout-programmatically