Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Android

Cách đặt màu nền ngẫu nhiên cho RecyclerView trong Android

Mục tiêu

Demo cách gán màu nền ngẫu nhiên cho từng item trong RecyclerView bằng lớp Random và Color.argb().

Các bước chính

Bước 1-4: Project, Dependency, Layout, MainActivity

Giống ví dụ sắp xếp (ID 1003060859), sử dụng LinearLayoutManager và DividerItemDecoration.

Bước 5: StudentAdapter.java - Logic màu ngẫu nhiên

class StudentAdapter extends RecyclerView.Adapter<StudentAdapter.MyViewHolder> {
    private List<StudentData> studentDataList;

    public StudentAdapter(List<StudentData> studentDataList) {
        this.studentDataList = studentDataList;
    }

    @Override
    public void onBindViewHolder(MyViewHolder holder, int position) {
        StudentData data = studentDataList.get(position);
        
        // Tạo màu ngẫu nhiên ARGB
        Random rnd = new Random();
        int currentColor = Color.argb(255, rnd.nextInt(256), rnd.nextInt(256), rnd.nextInt(256));
        holder.parent.setBackgroundColor(currentColor);
        
        holder.name.setText(data.name);
        holder.age.setText(String.valueOf(data.age));
    }
    // ... các phương thức khác
}

Giải thích: Color.argb(alpha, red, green, blue) tạo màu từ 4 thành phần. rnd.nextInt(256) sinh số 0-255 cho mỗi kênh màu. Alpha=255 nghĩa là không trong suốt.

Bước 6: Layout item (LinearLayout ngang, 2 TextView weight 0.5)

<LinearLayout android:orientation="horizontal" android:weightSum="1" ...>
    <TextView android:id="@+id/name" android:layout_width="0dp" android:layout_weight="0.5" ... />
    <TextView android:id="@+id/age" android:layout_width="0dp" android:layout_weight="0.5" ... />
</LinearLayout>

Lưu ý: Layout này không dùng CardView, màu nền được set trực tiếp lên LinearLayout cha (id=parent).

Bước 7: Model StudentData.java

Giống các ví dụ trước.

Kết quả

Màn hình ban đầu với dữ liệu đã sort và màu ngẫu nhiên:

Cách đặt màu nền ngẫu nhiên cho RecyclerView trong Android

Cuộn xuống thấy các item tiếp theo với màu khác nhau:

Cách đặt màu nền ngẫu nhiên cho RecyclerView trong Android