我有一个简单的布局:一个固定高度的 TextView,三个 ImageView 对象锚定在 View 的底部。
如何以编程方式更改每个 ImageView 的高度,使它们在一定范围内变化(低于 TextView 10dp、16dp)?具体而言,我的 Activity 获得了一个百分比列表(介于 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);
最佳答案
如果您所说的“高度”是指 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
,但您使用哪种方法取决于布局的设置方式。
关于android - 以编程方式更改约束布局中的高度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46588387/