我想在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;
}
答案 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;
}