How to add different weight to ConstraintLayout views

前端 未结 3 968
死守一世寂寞
死守一世寂寞 2020-12-08 06:08

In my layout, I have a ConstraintLayout containing two TextView elements. They are currently the same size, but I would like them to have different

3条回答
  •  攒了一身酷
    2020-12-08 07:05

    In XML

    Create a horizontal chain, and then use the app:layout_constraintHorizontal_weight attribute:

    
    
    
        
    
        
    
    
    

    In Java

    Create your views and add them to the parent ConstraintLayout. You will need to give them each an id in order for everything to work; you can use View.generateViewId() or you can define an id resource for them.

    // this will be MATCH_CONSTRAINTS width and 48dp height
    int height = (int) (getResources().getDisplayMetrics().density * 48);
    ViewGroup.LayoutParams params = new ViewGroup.LayoutParams(0, height);
    
    View left = new View(this);
    left.setId(R.id.one);
    parent.addView(left, params);
    
    View right = new View(this);
    right.setId(R.id.two);
    parent.addView(right, params);
    

    Then create a ConstraintSet object and create your chain:

    ConstraintSet set = new ConstraintSet();
    set.clone(parent);
    
    int[] chainIds = { R.id.one, R.id.two }; // the ids you set on your views above
    float[] weights = { 6, 4 };
    set.createHorizontalChain(ConstraintSet.PARENT_ID, ConstraintSet.LEFT,
                              ConstraintSet.PARENT_ID, ConstraintSet.RIGHT,
                              chainIds, weights, ConstraintSet.CHAIN_SPREAD);
    
    set.applyTo(parent);
    

提交回复
热议问题