Android : How to programmatically set layout_constraintRight_toRightOf “parent”

后端 未结 3 631
予麋鹿
予麋鹿 2020-12-02 20:03

I have a view in ConstrainLayout as follows.



        
相关标签:
3条回答
  • 2020-12-02 20:25

    Here is an example of setting a button to the bottom of parent view using java code:

    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);
    
    }
    

    to achieve something like this,

    app:layout_constraintLeft_toLeftOf="@+id/parent" 
    

    your java code should look like this

    set.connect(YOURVIEW.getId(),ConstraintSet.LEFT,ConstraintSet.PARENT_ID,ConstraintSet.LEFT,0);
    

    and to achieve something like this,

    layout_constraintLeft_toRightOf="@+id/parent"
    

    your java code should look like this,

    set.connect(YOURVIEW.getId(),ConstraintSet.LEFT,ConstraintSet.PARENT_ID,ConstraintSet.RIGHT,0);
    

    Here, I'm assuming android:id="@+id/parent" is the id of your parent ConstraintLayout .

    0 讨论(0)
  • 2020-12-02 20:34

    Use 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()
        }
    }
    
    0 讨论(0)
  • 2020-12-02 20:44

    constraintSet = new ConstraintSet(); and so on

    Did not work for me anyhow.

    Solved by

      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);
    
    0 讨论(0)
提交回复
热议问题