Android:如何以编程方式设置layout_constraintRight_toRightOf"parent"

Rel*_*elm 29 android android-support-library android-constraintlayout

我在ConstrainLayout中有一个视图如下.

<TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:maxWidth="260dp"
        android:textColor="#FFF"
        android:textSize="16sp"
        app:layout_constraintLeft_toLeftOf="@+id/parent"
        app:layout_constraintTop_toBottomOf="@id/message_date"
        android:id="@+id/text_main"
        />
Run Code Online (Sandbox Code Playgroud)

我想根据某些条件将视图更改为app:layout_constraintLeft_toLeftOf="@+id/parent"layout_constraintLeft_toRightOf="@+id/parent"在recycleViewHolder中以编程方式.

Dar*_*oni 59

以下是使用java代码将按钮设置到父视图底部的示例:

ConstraintLayout constraintLayout;
ConstraintSet constraintSet;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    constraintLayout = (ConstraintLayout) findViewById(R.id.activity_main_constraint_layout);

    Button button = new Button(this);
    button.setText("Hello");
    constraintLayout.addView(button);

    constraintSet = new ConstraintSet();
    constraintSet.clone(constraintLayout);

    constraintSet.connect(button.getId(), ConstraintSet.LEFT, constraintLayout.getId(), ConstraintSet.RIGHT, 0);
    constraintSet.constrainDefaultHeight(button.getId(), 200);
    constraintSet.applyTo(constraintLayout);

}
Run Code Online (Sandbox Code Playgroud)

实现这样的目标,

app:layout_constraintLeft_toLeftOf="@+id/parent" 
Run Code Online (Sandbox Code Playgroud)

你的java代码应该是这样的

set.connect(YOURVIEW.getId(),ConstraintSet.LEFT,ConstraintSet.PARENT_ID,ConstraintSet.LEFT,0);
Run Code Online (Sandbox Code Playgroud)

并实现这样的目标,

layout_constraintLeft_toRightOf="@+id/parent"
Run Code Online (Sandbox Code Playgroud)

你的java代码应该是这样的,

set.connect(YOURVIEW.getId(),ConstraintSet.LEFT,ConstraintSet.PARENT_ID,ConstraintSet.RIGHT,0);
Run Code Online (Sandbox Code Playgroud)

在这里,我假设android:id="@+id/parent"是您的父ConstraintLayout的id.


小智 14

约束集=新的约束集();等等

无论如何都不适合我。

已解决

  LayoutParams layoutParams = (LayoutParams) viewToChange.getLayoutParams();
    layoutParams.leftToLeft = anotherViewId;
    layoutParams.rightToRight =anotherViewId;
    layoutParams.topToTop = anotherViewId;
    layoutParams.bottomToBottom = anotherViewId;
    layoutParams.startToStart =anotherViewId;
    layoutParams.endToEnd = anotherViewId;
    viewToChange.setLayoutParams(layoutParams);
Run Code Online (Sandbox Code Playgroud)


onm*_*133 5

id

class MyLayout(context: Context) : ConstraintLayout(context) {

    fun show() {
        val view = ImageView(context)
        addView(view)
        val params = view.layoutParams as ConstraintLayout.LayoutParams
        params.height = 100 
        params.width = 50
        params.rightToRight = id
        view.requestLayout()
    }
}
Run Code Online (Sandbox Code Playgroud)