如何以编程方式修改可绘制角 Android Java
How to modify drawable corners programmatically Android Java
我需要从 Java.
以编程方式修改 xml 可绘制圆角半径
XML 看起来像这样(可以修改):
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<corners android:bottomRightRadius="32dp"
android:bottomLeftRadius="32dp"
android:topRightRadius="32dp"
android:topLeftRadius="32dp"/>
</shape>
我已经走到这一步了。
Resources res = context.getResources();
Drawable customRoundedButton = ResourcesCompat.getDrawable(res, R.drawable.custom_rounded_button, null);
// customRoundedButton somehow modify corners??
// customRoundedButton.setCornerRadii(16); // What I would like to do in pseudo code
PiaInterfaceConfiguration.getInstance().setButtonRoundCorner(R.drawable.custom_rounded_button);
问题是 PiaInterfaceConfiguration 只接受 int 形式的 drawable 引用。
如果你的 PiaInterfaceConfiguration
只需要资源 id int
那么你不能改变这些角,你必须创建另一个不可改变的 XML 或修改这个 class(添加 int roundCorner
参数并将其设置在此 class 中,就像您尝试使用注释代码一样)
编辑:要设置圆角半径,您必须使用属于 GradientDrawable
的 setCornerRadius(float)
方法。所以你的 Drawable customRoundedButton
必须转换为 GradientDrawable
(即使有纯色,不使用渐变“功能”)
Drawable customRoundedButton = ...
if (customRoundedButton instanceof GradientDrawable) { // check just for safety
((GradientDrawable) customRoundedButton).setCornerRadius(22f); // float
}
我需要从 Java.
以编程方式修改 xml 可绘制圆角半径XML 看起来像这样(可以修改):
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<corners android:bottomRightRadius="32dp"
android:bottomLeftRadius="32dp"
android:topRightRadius="32dp"
android:topLeftRadius="32dp"/>
</shape>
我已经走到这一步了。
Resources res = context.getResources();
Drawable customRoundedButton = ResourcesCompat.getDrawable(res, R.drawable.custom_rounded_button, null);
// customRoundedButton somehow modify corners??
// customRoundedButton.setCornerRadii(16); // What I would like to do in pseudo code
PiaInterfaceConfiguration.getInstance().setButtonRoundCorner(R.drawable.custom_rounded_button);
问题是 PiaInterfaceConfiguration 只接受 int 形式的 drawable 引用。
如果你的 PiaInterfaceConfiguration
只需要资源 id int
那么你不能改变这些角,你必须创建另一个不可改变的 XML 或修改这个 class(添加 int roundCorner
参数并将其设置在此 class 中,就像您尝试使用注释代码一样)
编辑:要设置圆角半径,您必须使用属于 GradientDrawable
的 setCornerRadius(float)
方法。所以你的 Drawable customRoundedButton
必须转换为 GradientDrawable
(即使有纯色,不使用渐变“功能”)
Drawable customRoundedButton = ...
if (customRoundedButton instanceof GradientDrawable) { // check just for safety
((GradientDrawable) customRoundedButton).setCornerRadius(22f); // float
}