Issue
I am setting the background color for each row in my customadapter as
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));
}
My array of color
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};
this is the function 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;
}
the row background is set to two color. Is that the random number is generated same all the time?
Solution
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
}
This will randomly generate the four different color in your listview.
inside adapter
@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:
class ViewHolder{
public TextView textView;
}
adapter custom layout :
<?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"/>
</LinearLayout>
Answered By - Rathiga Jesika
Answer Checked By - Katrina (JavaFixing Volunteer)