即使已经在 xml 中设置了背景,如何在运行时制作圆角按钮
how to make rounded corners button on runtime even if background is already set in xml
我了解如何使用 GradientDrawable
使 Button
具有圆角。我现在的问题是,如果我已经在 xml 中设置了我的背景并通过
检索它
int[] attrsArray = new int[] {
android.R.attr.background
};
TypedArray ta = context.obtainStyledAttributes(attrs, attrsArray);
Drawable background = ta.getDrawable(0);
ta.recycle();
所以我现在有一个 Drawable
类型的背景。接下来我要做的是调用 setBackgroundDrawable()
并传递可绘制背景,但我无法使用 Drawable
类型设置圆角。我也不能只将它转换为 GradientDrawable
。有没有办法做到这一点?这种方式让事情变得容易多了,因为我可以给 Button
任何背景和圆角。
谢谢
不确定您的用例是否与我的相同,但我曾经做过类似的事情,我有一个不可见的 Button,它后面有一个 RoundedImageView。 RoundedImageView 如下:
https://github.com/vinc3m1/RoundedImageView
使用那个class你可以设置图像的半径。
我了解如何使用 GradientDrawable
使 Button
具有圆角。我现在的问题是,如果我已经在 xml 中设置了我的背景并通过
int[] attrsArray = new int[] {
android.R.attr.background
};
TypedArray ta = context.obtainStyledAttributes(attrs, attrsArray);
Drawable background = ta.getDrawable(0);
ta.recycle();
所以我现在有一个 Drawable
类型的背景。接下来我要做的是调用 setBackgroundDrawable()
并传递可绘制背景,但我无法使用 Drawable
类型设置圆角。我也不能只将它转换为 GradientDrawable
。有没有办法做到这一点?这种方式让事情变得容易多了,因为我可以给 Button
任何背景和圆角。
谢谢
不确定您的用例是否与我的相同,但我曾经做过类似的事情,我有一个不可见的 Button,它后面有一个 RoundedImageView。 RoundedImageView 如下:
https://github.com/vinc3m1/RoundedImageView
使用那个class你可以设置图像的半径。