如何在ImageView上设置随机颜色?

时间:2019-03-09 08:35:25

标签: java android android-imageview

我想在ImageView上设置随机颜色。我的颜色排成阵列。如何在ImageView上随机设置我的颜色?

  

我的代码:

@Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment

            View RootView1 = inflater.inflate(R.layout.fragment_diary, container, false);
            String[] colorsForDiary = getResources().getStringArray(R.array.mdcolor_random);
            Random rand = new Random();
            String colorsFinal = String.valueOf(rand.nextInt(colorsForDiary.length));
            ImageView imageView = (ImageView)RootView.findViewById(R.id.image_fir);
            imageView.setColorFilter(ContextCompat.getColor(getContext(), Integer.parseInt(colorsFinal)));
            return RootView1;
    }

2 个答案:

答案 0 :(得分:0)

您可以使用此:

Random rnd = new Random(); 
int color = Color.argb(255, rnd.nextInt(256), rnd.nextInt(256), rnd.nextInt(256));   
imageView.setBackgroundColor(color);

答案 1 :(得分:0)

array.xml中的数组下面添加

<string-array name="colors">
        <item>#000000</item>
        <item>#FFFFFF</item>
        <item>#121212</item>
        <item>#8A1F1F</item>
        <item>#BC1212</item>
    </string-array>

在您的Java中。

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment

    View RootView1 = inflater.inflate(R.layout.fragment_diary, container, false);

    ImageView imageView = (ImageView) RootView.findViewById(R.id.image_fir);
    String[] colorlist = getResources().getStringArray(R.array.colors);
    String color = colorlist[randInt(0, (colorlist.length - 1)))]
    imageView.setBackgroundColor(Color.parseColor(color));
    return RootView1;
}

public static int randInt(int min, int max) {

        // Usually this can be a field rather than a method variable
        Random rand = new Random();
        // nextInt is normally exclusive of the top value,
        // so add 1 to make it inclusive
        int randomNum = rand.nextInt((max - min) + 1) + min;

        return randomNum;
    }