使用 setLayoutParams 方法修改 View 的宽度并不会影响其圆角 shape 背景的显示。这是因为圆角 shape 背景是根据 View 的宽高比例来绘制的,而不是根据实际的宽度来绘制的。

要实现修改 View 的宽度后,圆角 shape 背景也跟着改变,可以尝试以下方法:

  1. 使用 View.setBackgroundDrawable 方法设置圆角 shape 背景,而不是使用 xml 中的 android:background 属性。这样,当调用 setLayoutParams 方法修改 View 的宽度后,再调用 setBackgroundDrawable 方法重新设置背景,圆角 shape 背景会根据新的宽度来重新绘制。
// 设置圆角 shape 背景
GradientDrawable shape = new GradientDrawable();
shape.setShape(GradientDrawable.RECTANGLE);
shape.setCornerRadius(radius);
view.setBackgroundDrawable(shape);

// 修改 View 的宽度
LayoutParams layoutParams = view.getLayoutParams();
layoutParams.width = newWidth;
view.setLayoutParams(layoutParams);
  1. 使用 setScaleX 方法修改 View 的水平缩放比例,同时调整圆角 shape 背景的圆角半径,使其与缩放后的宽度保持一致。
// 修改 View 的宽度
LayoutParams layoutParams = view.getLayoutParams();
layoutParams.width = newWidth;
view.setLayoutParams(layoutParams);

// 修改圆角 shape 背景的圆角半径
GradientDrawable shape = (GradientDrawable) view.getBackground();
shape.setCornerRadius(radius * view.getScaleX());

请注意,以上方法仅适用于圆角 shape 背景,如果使用其他类型的背景,可能需要使用其他的方法来实现。

Android 开发:如何让修改 View 宽度后圆角背景也跟着改变

原文地址: https://www.cveoy.top/t/topic/plKG 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录