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

How to set random color on ImageView?

我想在 ImageView 上设置随机颜色。我的颜色发生在数组中。如何在 ImageView 上随机设置我的颜色?

My code:

@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;
    }

你可以使用这个:

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

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;
    }