set percent width constraintlayout Android programmatically

耗尽温柔 提交于 2019-12-23 20:57:06

问题


For constraint layout v1.1.x in Android we can set height and width as percentage. Similarly, need to set view width and height as percent in Android programmatically: for example, this code is written in xml for some constraint layout:

<!-- the widget will take 40% of the available space -->
    app:layout_constraintWidth_default="percent"
    app:layout_constraintWidth_percent="0.4"

what will be its java code for doing it runtime?


回答1:


You need to use ConstraintSet - Reference

This class allows you to define programmatically a set of constraints to be used with ConstraintLayout. It lets you create and save constraints, and apply them to an existing ConstraintLayout. ConstraintsSet can be created in various ways:

mConstraintLayout = (ConstraintLayout) findViewById(R.id.myconstraint_layout)

ConstraintSet set = new ConstraintSet();

// Add constrains - Here R.id.myconstraint_layout is the Id of your constraint layout
set.constrainPercentHeight(R.id.myconstraint_layout, 0.4);
set.constrainPercentWidth(R.id.myconstraint_layout, 0.4);

// Apply the changes - mConstraintLayout is reference to the desired view
set.applyTo(mConstraintLayout); 

You can call those height width percentage methods on this set

  • constrainPercentHeight(int viewId, float percent)
  • constrainPercentWidth(int viewId, float percent)

And apply those constraints to your Constraint Layout like this

set.applyTo(mConstraintLayout); 



回答2:


Note sure if this is better or worse, but there is another way to do this than the proposed answer:

// Kotlin:
(myView.layoutParams as ConstraintLayout.LayoutParams).matchConstraintPercentWidth = value
myView.requestLayout()

// Java:
(myView.layoutParams (ConstraintLayout.LayoutParams)).matchConstraintPercentWidth = value
myView.requestLayout()


来源:https://stackoverflow.com/questions/51420888/set-percent-width-constraintlayout-android-programmatically

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!