【问题标题】:Programmatically change height in constraint layout?以编程方式更改约束布局中的高度?
【发布时间】:2018-03-17 05:39:42
【问题描述】:

我有一个简单的布局:一个固定高度的 TextView,其中三个 ImageView 对象锚定在视图的底部。

如何以编程方式更改每个 ImageView 的高度,使它们在一定范围内变化(10dp,TextView 下方 16dp)?具体来说,我的活动得到一个百分比列表(介于 0 和 1 之间),表示每个“条”应占用多少垂直空间。

我尝试了以下方法但没有成功:

// No visible difference
imgView.setMinHeight(newHeight);

// No change to height, but horizontal constrained was messed up
imgView.setLayoutParams(new LayoutParam(imgView.getWidth(), newHeight);

【问题讨论】:

标签: android android-layout android-constraintlayout


【解决方案1】:

如果“高度”是指ImageView 的绝对上下尺寸,则可以执行以下操作以将ImageView 的高度加倍。您可以将高度设置为您想要的值。

ImageView iv = (ImageView) findViewById(R.id.imageView);
ConstraintLayout.LayoutParams lp = (ConstraintLayout.LayoutParams) iv.getLayoutParams();
lp.height = lp.height * 2;
iv.setLayoutParams(lp);

见ConstraintLayout.LayoutParams。

但是,如果“高度”是指ImageView 的垂直位置,您可以执行以下操作来更改ImageView 的垂直偏差(假设您使用的是ConstraintLaytout):

ConstraintSet cs = new ConstraintSet();
ConstraintLayout layout = (ConstraintLayout) findViewById(R.id.layout);
cs.clone(layout);
cs.setVerticalBias(R.id.imageView, 0.25f);
cs.applyTo(layout);

见setVerticalBias。

还有其他方法可以移动有关布局的ImageView,但您使用哪种方法取决于您的布局是如何设置的。

【讨论】:

    猜你喜欢
    • 2014-01-22
    • 2015-04-02
    • 2015-07-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-01
    相关资源
    最近更新 更多