使用drawable制作形状

时间:2018-06-10 07:22:42

标签: android gradient shape

当您构建Android应用程序项目时,会有一个背景颜色预设文件,如:

<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle" >
   <gradient
      android:startColor="#ffffff"
      android:centerColor="#00ffff"
      android:endColor="#000000"
      android:type="linear"
      android:angle="90"/>

使用android:startColor,android:centerColor,android:endColor,android:type,android:angle的字符串值,我们如何以编程方式制作这个渐变?

1 个答案:

答案 0 :(得分:0)

尝试从这段代码中激发灵感,我想,你会得到主要的想法:

GradientDrawable drawable = new GradientDrawable(GradientDrawable.Orientation.TOP_BOTTOM, new int[]{startColor, endColor});
drawable.setStroke(strokeIntLength, strokeColor);

GradientDrawable drawableSelected = new GradientDrawable(GradientDrawable.Orientation.TOP_BOTTOM, new int[]{startColorDark, endColorDark});
drawableSelected.setStroke(strokeIntLength, strokeColorDark);

StateListDrawable states = new StateListDrawable();
states.addState(new int[]{android.R.attr.state_selected, android.R.attr.state_pressed}, drawable);
states.addState(new int[]{android.R.attr.state_pressed}, drawableSelected);
states.addState(new int[]{android.R.attr.state_selected}, drawableSelected);
states.addState(new int[]{android.R.attr.state_checked}, drawableSelected);
states.addState(new int[]{}, drawable);

button.setBackgroundDrawable(states);