我有麻烦应用梯度背景到线性布局。
从我所读到的来看,这应该是相对简单的,但它似乎并不奏效。作为参考,我正在2.1-update1上开发。
header_bg.xml:
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<gradient
android:angle="90"
android:startColor="#FFFF0000"
android:endColor="#FF00FF00"
android:type="linear"/>
</shape>
main_header.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="50dip"
android:orientation="horizontal"
android:background="@drawable/header_bg">
</LinearLayout>
如果我改变@drawable/header_bg的颜色-例如,#FF0000,它工作得很好。我是不是遗漏了什么明显的东西?
好的,我已经设法解决这个使用选择器。参见下面的代码:
main_header.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="50dip"
android:orientation="horizontal"
android:background="@drawable/main_header_selector">
</LinearLayout>
main_header_selector.xml:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item>
<shape>
<gradient
android:angle="90"
android:startColor="#FFFF0000"
android:endColor="#FF00FF00"
android:type="linear" />
</shape>
</item>
</selector>
希望这能帮助到有同样问题的人。
您可以使用自定义视图来做到这一点。有了这个解决方案,它就完成了项目中所有颜色的渐变形状:
class GradientView(context: Context, attrs: AttributeSet) : View(context, attrs) {
// Properties
private val paint: Paint = Paint()
private val rect = Rect()
//region Attributes
var start: Int = Color.WHITE
var end: Int = Color.WHITE
//endregion
override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) {
super.onSizeChanged(w, h, oldw, oldh)
// Update Size
val usableWidth = width - (paddingLeft + paddingRight)
val usableHeight = height - (paddingTop + paddingBottom)
rect.right = usableWidth
rect.bottom = usableHeight
// Update Color
paint.shader = LinearGradient(0f, 0f, width.toFloat(), 0f,
start, end, Shader.TileMode.CLAMP)
// ReDraw
invalidate()
}
override fun onDraw(canvas: Canvas) {
super.onDraw(canvas)
canvas.drawRect(rect, paint)
}
}
我还用这个自定义视图创建了一个开源项目GradientView:
https://github.com/lopspower/GradientView
implementation 'com.mikhaellopez:gradientview:1.1.0'
在XML可绘制文件:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item>
<shape>
<gradient android:angle="90"
android:endColor="#9b0493"
android:startColor="#38068f"
android:type="linear" />
</shape>
</item>
</selector>
在你的布局文件:android:background="@drawable/gradient_background"
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@drawable/gradient_background"
android:orientation="vertical"
android:padding="20dp">
.....
</LinearLayout>