如何以编程方式在PercentRelativeLayout中设置percentHeight

时间:2017-03-27 16:20:40

标签: android android-percentrelativelayout

我想以百分比设置PercentRelativeLayout的高度。

PercentRelativeLayout layout = new PercentRelativeLayout(this);
        PercentRelativeLayout.LayoutParams llp = new PercentRelativeLayout.LayoutParams(PercentRelativeLayout.LayoutParams.MATCH_PARENT, 50%);
        layout.setLayoutParams(llp);

        myLayout.addView(layout);

我想在LayoutParams中使用percentHeight(50%),而不是Match_Parent或Wrap_Content。

1 个答案:

答案 0 :(得分:2)

此代码:

LinearLayout rootLayout = (LinearLayout) findViewById(R.id.root);
PercentRelativeLayout percentRelativeLayout = new PercentRelativeLayout(this);
percentRelativeLayout.setBackgroundColor(ContextCompat.getColor(this, R.color.colorAccent));
rootLayout.addView(percentRelativeLayout);

Button button = new Button(this);
percentRelativeLayout.addView(button);
PercentRelativeLayout.LayoutParams params = (PercentRelativeLayout.LayoutParams) button.getLayoutParams();
PercentLayoutHelper.PercentLayoutInfo info = params.getPercentLayoutInfo();
info.heightPercent = 0.5f;

将有此输出:

PercentRelativeLayout takes half the screen height