2017-01-04 3 views
1

я устанавливаю цвет фона для каждой строки в моем customadapter какслучайный цвет для каждой строки в виде списка из массива цветов

public View getView(int position, View convertView, ViewGroup parent) { 





    if (inflater == null) 
     inflater = (LayoutInflater) activity 
       .getSystemService(Context.LAYOUT_INFLATER_SERVICE); 
    if (convertView == null) { 
     convertView = inflater.inflate(R.layout.coupon_list_row, null); 
     int temp_index = ExtraFu.randInt(0, 9); 
     convertView.setBackgroundColor(color_arr[temp_index]); 
     Log.d("temp_index", String.valueOf(temp_index)); 
    } 

Мой массив цвета

int color_arr[]={R.color.cred,R.color.cpink,R.color.cpurple,R.color.cdpurple,R.color.cindigo,R.color.cblue,R.color.cdorange,R.color.cgreen,R.color.cbroun,R.color.ccyan}; 

это функция randInt

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

сравнение positio n число и цвет массива в условии if. с петлей установите цвет фона в convertview. –

+0

Я не могу этого сделать, потому что список динамический и может содержать n количество элементов. –

ответ

2
if (position%4 == 0){ 
      // set convertView Background   
     } else if (position%4 == 1){ 
      // set convertView Background 
     } else if (position%4 == 2){ 
      // set convertView Background 
     } else if (position%4 == 3){ 
      // set convertView Background 
     } 

Это будет случайным образом генерировать четыре разных цвета в вашем списке.

внутри адаптера

@Override 
    public View getView(int position, View convertView, ViewGroup parent) { 
     ViewHolder holder; 
     if (convertView == null) { 
      convertView = lv.inflate(res, null); 
      holder = new ViewHolder(); 
      holder.textView = (TextView)convertView.findViewById(R.id.text); 
      convertView.setTag(holder); 

     } else { 
      holder = (ViewHolder) convertView.getTag(); 
     } 

     if (position%4 == 0){ 
      holder.textView.setBackgroundColor(Color.parseColor("#1e86cf")); 
     } else if (position%4 == 1){ 
      holder.textView.setBackgroundColor(Color.parseColor("#2ca0ea")); 
     } else if (position%4 == 2){ 
      holder.textView.setBackgroundColor(Color.parseColor("#2cc4ea")); 
     } else if (position%4 == 3){ 
      holder.textView.setBackgroundColor(Color.parseColor("#2ceae3")); 
     } 
     return convertView; 
    } 

ViewHolder Класс:

class ViewHolder{ 
     public TextView textView; 
    } 

адаптер пользовательский макет:

<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
android:orientation="vertical" android:layout_width="match_parent" 
android:layout_height="match_parent"> 
<TextView 
    android:id="@+id/text" 
    android:layout_width="match_parent" 
    android:layout_height="wrap_content" 
    android:gravity="center" 
    android:padding="15dp" 
    android:textColor="@color/white" 
    android:textSize="20sp" 
    android:textStyle="bold"/> 

+0

Итак, если у меня есть n количество элементов? и что случилось с этим случайным числом? –

+0

в моем ответе повторит четыре цвета. случайным образом это может измениться. –

+0

Я сделал то же самое, что вы написали. но вместо 4 я использую 10, но все равно получаю только два разных цвета. –

0

Используйте приведенный ниже код, чтобы получить Случайный цвет

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

Но у меня уже есть набор цветов –

+0

Это генерирует только 2 цвета. –

+1

нет, этот код будет генерировать все цвета случайно не только двух цветов. но случайным образом, чтобы он случайно повторял цвета. вы можете проверить его снова. если у вас нет каких-либо ограничений цветов, вы можете использовать вышеприведенный код. –

2

Я редактировал код

вам нужно использовать ниже линию я проверил свою рабочую FinR для моего макета

convertView.setBackgroundResource(color_arr[rnd]); 

Обновленного код не проверено на моей стороне

if (inflater == null) 
     inflater = (LayoutInflater) activity 
       .getSystemService(Context.LAYOUT_INFLATER_SERVICE); 
    if (convertView == null) { 
     convertView = inflater.inflate(R.layout.coupon_list_row, null); 



int color_arr[]= {R.color.cred,R.color.cpink,R.color.cpurple,R.color.cdpurple,R.color.cindigo,R.color.cblue,R.color.cdorange,R.color.cgreen,R.color.cbroun,R.color.ccyan}; 
int rnd = new Random().nextInt(color_arr.length); 


     //convertView.setBackgroundColor(color_arr[temp_index]); 

     convertView.setBackgroundResource(color_arr[rnd]); 

    } 

Ссылка Кодекс, который я попробовал и работает нормально так делать потребного изменения

int color_arr[] = {R.color.colorAccent, R.color.colorPrimary, R.color.colorPrimaryDark}; 


    int rnd = new Random().nextInt(color_arr.length); 

    linearLayout.setBackgroundResource(color_arr[rnd]); 
2

Для Random Color Generation:

private int getRandomColor() { 
    SecureRandom rgen = new SecureRandom(); 
    return Color.HSVToColor(150, new float[]{ 
     rgen.nextInt(359), 1, 1 
    }); 
} 

И установить BackGroundColor каждого элемента после извлечения позиция позиции:

holder.textView.setBackGroundColor(getRandomColor()); 
Смежные вопросы