有写场景需要在Java代码中移除xml中配置的百分比属性,如:
app:layout_constraintHeight_percent="0.3" app:layout_constraintWidth_percent="0.722"
在Java中移除以百分比属性的具体操作:
if (lp instanceof ConstraintLayout.LayoutParams) { ((ConstraintLayout.LayoutParams) lp).matchConstraintPercentHeight = 1f; ((ConstraintLayout.LayoutParams) lp).matchConstraintDefaultHeight = 0;/*spread 默认的,非percent*/ }
matchConstraintPercentHeight = 1
是ConstraintLayout.LayoutParams的默认值;
matchConstraintDefaultHeight = 0
是spread模式,为默认值。
其它的值在约束布局的values.xml中有定义:
<attr name="layout_constraintWidth_default"> <enum name="spread" value="0"/> <enum name="wrap" value="1"/> <enum name="percent" value="2"/> </attr> <attr name="layout_constraintHeight_default"> <enum name="spread" value="0"/> <enum name="wrap" value="1"/> <enum name="percent" value="2"/> </attr>
可以看到,百分比模式的值为2。
在ConstraintLayout的源码中也能看到:
case 35: this.matchConstraintPercentWidth = Math.max(0.0F, a.getFloat(attr, this.matchConstraintPercentWidth)); this.matchConstraintDefaultWidth = 2; break; case 38: this.matchConstraintPercentHeight = Math.max(0.0F, a.getFloat(attr, this.matchConstraintPercentHeight)); this.matchConstraintDefaultHeight = 2; break;