ConstraintLayout: How to add several views programmatically?

前端 未结 1 1129
伪装坚强ぢ
伪装坚强ぢ 2020-12-29 13:57

I want to add 2 buttons to a ConstraintLayout. My current code is as following:

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(saved         


        
相关标签:
1条回答
  • 2020-12-29 14:19

    Here is the working code of what you want to achieve

      @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            ConstraintLayout layout = (ConstraintLayout) findViewById(R.id.activity_main);
            ConstraintSet set = new ConstraintSet();
            set.clone(layout);
    
            //Button 1:
            Button button = new Button(this);
            button.setText("Hello");
            button.setId(100);           // <-- Important
            layout.addView(button);
            set.connect(button.getId(), ConstraintSet.BOTTOM, ConstraintSet.PARENT_ID, ConstraintSet.BOTTOM, 0);
            set.connect(button.getId(),ConstraintSet.RIGHT,ConstraintSet.PARENT_ID,ConstraintSet.RIGHT,0);
            set.connect(button.getId(),ConstraintSet.LEFT,ConstraintSet.PARENT_ID,ConstraintSet.LEFT,0);
            set.constrainHeight(button.getId(), 200);
            set.applyTo(layout);
    
    
            //Button 2:
            Button newButton = new Button(this);
            newButton.setText("Yeeey");
            layout.addView(newButton);
            set.connect(newButton.getId(), ConstraintSet.BOTTOM, button.getId(), ConstraintSet.TOP, 0);
            set.connect(newButton.getId(),ConstraintSet.RIGHT,ConstraintSet.PARENT_ID,ConstraintSet.RIGHT,0);
            set.connect(newButton.getId(),ConstraintSet.LEFT,ConstraintSet.PARENT_ID,ConstraintSet.LEFT,0);
            set.constrainHeight(newButton.getId(), 200);
            set.applyTo(layout);
    
    
        }
    

    Important:
    If id is not set explicitly, all the elements will get the same id(-1).

    0 讨论(0)
提交回复
热议问题