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

问题描述 投票:0回答:2

我想在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;
    }
java android android-imageview
2个回答
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;
    }

0
投票

你可以用这个:

Random rnd = new Random(); 
int color = Color.argb(255, rnd.nextInt(256), rnd.nextInt(256), rnd.nextInt(256));   
imageView.setBackgroundColor(color);
© www.soinside.com 2019 - 2024. All rights reserved.