目前我有3个可绘制的XML文件,用于定义3个独立的渐变。这些渐变在我的代码中动态设置为imageView的背景颜色(工作正常)。
示例:drawable \ morningsky.xml
<?xml version="1.0" encoding="utf-8"?>
<item android:bottom="4dp">
<shape>
<gradient
android:startColor="@color/blue"
android:endColor="@color/dark_blue"
android:angle="270" />
</shape>
示例:drawable \ eveningsky.xml
<?xml version="1.0" encoding="utf-8"?>
<item android:bottom="4dp">
<shape>
<gradient
android:startColor="@color/orange"
android:endColor="@color/yellow"
android:angle="270" />
</shape>
我在imageView中设置背景:
iv.setBackgroundResource(R.drawable.morningsky);
一切都很好,但是我真的需要为每个渐变使用多个不同的可绘制资源文件吗?有什么办法可以在一个可绘制文件中定义所有渐变,然后从我的代码中加载该渐变吗?
答案 0 :(得分:1)
你可以使用这样的东西
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<gradient
android:type="radial"
android:gradientRadius="300"
android:startColor="@android:color/white"
android:endColor="@android:color/transparent"
android:centerX="0.25"
android:centerY="0.5"/>
</shape>
</item>
<item>
<shape android:shape="rectangle">
<gradient
android:type="radial"
android:gradientRadius="300"
android:startColor="@android:color/white"
android:endColor="@android:color/transparent"
android:centerX="0.75"
android:centerY="0.5"/>
</shape>
</item>
</layer-list>
&#13;
答案 1 :(得分:0)
您可以使用选择器
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_pressed="true" android:drawable="@drawable\eveningsky.xml"/>
<item android:state_selected="true" android:drawable="@drawable\morningsky.xml"/>
<item android:drawable="@drawable\morningsky.xml"/>
</selector>
答案 2 :(得分:0)
您可以以编程方式执行此操作:
public void setShadeBackground(View v){
ShapeDrawable.ShaderFactory shaderFactory = new ShapeDrawable.ShaderFactory() {
@Override
public Shader resize(int width, int height) {
LinearGradient linearGradient = new LinearGradient(0, 0, width, height,
new int[] {
0xFF2583ED,
0xFF8220C9,
0xFFBC0BCC,
0xFFD625ED ,
0xFFD407AE ,
0xFFF2115C }, //substitute the correct colors for these
new float[] {
0, 0.30f,0.50f, 0.60f,0.70f, 1 },
Shader.TileMode.REPEAT);
return linearGradient;
}
};
PaintDrawable paint = new PaintDrawable();
paint.setShape(new RectShape());
paint.setShaderFactory(shaderFactory);
v.setBackgroundDrawable((Drawable)paint);
}