问题
I try to use the GradientDrawable to set a gradient to some backgrounds and buttons. Sadly the documentation is not very detailed.
What are the main attributes to configure the gradient? I understand start and endcolor but some of the other attributes could need some explanation.
At the moment I used images as the background for the buttons but a drawable defined in XML would be much nicer.
I try to get a look like this (It is a very light gradient): alt text http://janusz.de/~janusz/RedButton.png
回答1:
use this xml as background to the imageview.
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<gradient android:angle="90" android:startColor="#7c0000" android:endColor="#A71C1C"/>
</shape>
thats it.
回答2:
I will give the same answer as Praveen, but will try to explain the settings as well.
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<gradient
android:type="linear"
android:angle="-90"
android:startColor="#7c0000"
android:endColor="#A71C1C" />
</shape>
android:type
There are 3 types of gradients, the default and the one for this question is "linear". The other 2 are "radial" and "sweep".
android:angle
Counter-clockwise rotation of the gradient, where 0 is | start color --> end color | (horizontally).
android:startColor
Color the gradient starts from, start is defined by the rotation.
android:endColor
Color the gradient ends with, end is defined by the rotation.
android:centerColor
There can also be a color in between the start and end color, if desired.
回答3:
Code
I originally found this question because I wanted to do it in code. Here is how to do it programmatically.
int startColor = 0xfff6ee19; // yellow
int endColor = 0xff115ede; // blue
GradientDrawable gradientDrawable = new GradientDrawable(
GradientDrawable.Orientation.LEFT_RIGHT,
new int[] {startColor, endColor});
View myView = findViewById(R.id.my_view);
myView.setBackgroundDrawable(gradientDrawable);
The different orientations in the image at the top can be achieved by changing the Orientation
in the constructor.
XML
As already answered, this is how you do it in xml.
my_gradient_drawable.xml:
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<gradient
android:type="linear"
android:angle="0"
android:startColor="#f6ee19"
android:endColor="#115ede" />
</shape>
You set it to the background of some view. For example:
<View
android:layout_width="200dp"
android:layout_height="100dp"
android:background="@drawable/my_gradient_drawable"/>
See also
- How to make gradient background in android
- GradientDrawable documentation
来源:https://stackoverflow.com/questions/2666341/how-to-use-android-gradientdrawable