Search code examples
javaandroidandroid-imageview

How to set random color on ImageView?


I want to set random color on ImageView. My colors take place in array. How to set my colors in random on 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;
    }

Solution

  • Add below Array in array.xml

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

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