问题描述
我有一个来自 XML 资源的 drawable,我想使用该 drawable 但动态设置渐变颜色。 到目前为止,我有这样的事情:
<?xml version="1.0" encoding="utf-8"?>
<shape
xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<corners
android:radius="3dip">
</corners>
<gradient
android:angle="90"
android:type="linear"
android:startColor="#FFFFFFFF"
android:centerColor="#FFFF0000"
android:endColor="#FFFF0000">
</gradient>
</shape>
现在我想我可以通过在运行时获取可绘制对象、将其转换为 GradientDrawable 并使用一种方法来设置颜色来动态制作颜色。 但是 GradientDrawable 没有这样的方法,只能在构造函数中设置颜色。 我觉得这种情况很奇怪,因为渐变的所有其他方面都是可以设置的。 有没有比覆盖 onDraw() 并自己做渐变更简单的方法? 我尝试使用的一些类的记录非常差..
1楼
像这样创建一个 GradientDrawable 类:
public class RoundedDrawable extends GradientDrawable {
public RoundedDrawable(int shape, int solidColor, int strokeWidth,
int strokeColor, float[] fourRadii) {
this.mutate();
this.setShape(shape);
this.setColor(solidColor);
this.setStroke(strokeWidth, strokeColor);
this.setCornerRadii(fourRadii);
}
}
现在在您的 Activity 中使用它,如下所示:
公共类 AAActivity 扩展了 Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_transaction_layout);
RoundedDrawable customBg;
RelativeLayout relList = (RelativeLayout) findViewById(R.id.relList);
float radii[]={5.0f, 5.0f, 5.0f, 5.0f, 5.0f, 5.0f, 5.0f, 5.0f};
customBg = new RoundedDrawable(GradientDrawable.RECTANGLE,Color.parseColor("#FFFFFF"),
2, Color.parseColor("#8C8C8C"),radii);
relList.setBackgroundDrawable(customBg);
LinearLayout linearItemsRow = (LinearLayout) findViewById(R.id.linearItemsRow);
float[] rowRadii={5.0f, 5.0f, 5.0f, 5.0f, 0.0f, 0.0f, 0.0f, 0.0f};
customBg = new RoundedDrawable(GradientDrawable.RECTANGLE,Color.parseColor("#CBCBCB"),
0, 0, rowRadii);
linearItemsRow.setBackgroundDrawable(customBg);
}
}
希望这会有所帮助。
2楼
资源主要是静态的,通常不允许修改。
某些资源类型允许您“克隆”可变副本。
GradientDrawable
只允许您在构造器中设置颜色(如您所见),因此如果您想在运行时动态控制颜色,则需要在内部创建这些颜色,或者更好的是,从资源中选择固定数量的背景之一.
如前所述,使用setBackgroundDrawable()
在运行时安装背景。
无需通过判断,只需Get-R-Done!
3楼
班级
final class MyGradientDrawable extends GradientDrawable {
MyGradientDrawable(int fromColor, int toColor) {
super(Orientation.BOTTOM_TOP, new int[]{fromColor, toColor});
setCornerRadius(0);
setGradientType(LINEAR_GRADIENT);
setGradientRadius(90);
}
}
用法
final int firstColor = ContextCompat.getColor(requireContext(), R.color.my_first_color);
final int secondColor = ContextCompat.getColor(requireContext(), R.color.my_second_color);
final MyGradientDrawable myGradBg = new MyGradientDrawable(firstColor, secondColor);
myView.setBackground(myGradBg)
4楼
您可以动态设置为视图的背景可绘制。
view.setBackgroundDrawable(R.drawable.your_drawable_id);