如何以编程方式设置Random GradientDrawable Color - Android

时间:2015-12-01 13:39:26

标签: java android random shapes gradientdrawable

我的ProgressBar有问题。当我按下按钮“开始”随机功能从数组中选择一种颜色,但只有第一种颜色被设置为“背景”,当我再次点击一次选择新颜色但未设置为背景时。当我从应用程序退出并再次启动它时,会选择新颜色但现在只有一种颜色。当我按下按钮时,我想一直有不同的背景颜色。

activity_main.xml中

<ProgressBar
            android:id="@+id/circularProgressbar"
            style="?android:attr/progressBarStyleHorizontal"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_gravity="center"
            android:indeterminate="false"
            android:max="100"
            android:progress="100"
            android:progressDrawable="@drawable/circular"
            android:secondaryProgress="100" />

circular.xml

<?xml version="1.0" encoding="utf-8"?>

 <item  android:id="@+id/SecondaryProgress">  
    <shape
          android:innerRadiusRatio="5.2"
          android:shape="ring"
          android:useLevel="true"
          android:thicknessRatio="9.5">


    </shape>
</item>

MainActivity.java

public void Start(){

Random random = new Random();

String[] hex_colors = {"F8ED31", "000000", "F7931D", "ED1C24", "7A1777", "ED135A", "71BF43"};

int random_hex = random.nextInt(hex_colors.length); String color="#"+hex_colors[random_hex]; layers = (LayerDrawable) ContextCompat.getDrawable(this,R.drawable.circular); shape = ( GradientDrawable) layers.findDrawableByLayerId(R.id.SecondaryProgress); shape.setColor(Color.parseColor(color)); }

1 个答案:

答案 0 :(得分:0)

 private int[] colors = {Color.RED, Color.YELLOW, Color.BLUE, Color.CYAN, Color.GREEN};

 Random ranndom = new Random();
 int ranndomColor = ranndom.nextInt(5);
 shape.setColor(colors[ranndomColor]);