I am trying to set a recyclerview item color based on a boolean in kotlin. But when the recylerview loads, it will not set its color with the code I have. Also, If I change the background that is tied to the recycler view item via xml programmatically, it will not change it to the new drawable, but will reset it back to its basic form. Please just at least let me know why my setBackgroundColor line is not setting the list item background to the color I designate.
@RequiresApi(Build.VERSION_CODES.O)
override fun onBindViewHolder(holder: AlarmViewHolder, position: Int) {
val alarm = alarmList[position]
holder.itemView.apply {
if (alarm.amPm) {
setBackgroundColor(context.getColor(R.color.todays_day_color))
}
CodePudding user response:
I faced the same issue once Try to set the ackground color for your child's item
set background color for android:id="@ id/itemBackground"
layout_item.xml
e.g
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<LinearLayout
android:id="@ id/itemBackground"
android:padding="10dp"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:id="@ id/textView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="TextView" />
</LinearLayout>
</FrameLayout>
CodePudding user response:
To set the background color without struggling with radius, use MaterialCardView, you can set the corner radius, give stroke and set background color as well. In your layout use MaterialCardView as parent view.
<com.google.android.material.card.MaterialCardView
android:id="@ id/mcv"
app:cardBackgroundColor="@color/black_4a"
app:strokeColor="@color/cyan_500"
app:strokeWidth="1dp"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="@dimen/_5sdp"
android:elevation="14dp"
app:cardCornerRadius="5dp">
</com.google.android.material.card.MaterialCardView>
After this you can set the background color from adapter like
holder.mcv.setBackgroundColor(context.getColor(R.color.todays_day_color))
CodePudding user response:
Try writing the else loop also
I also once faced the same problem writing the else loop solved it for me.
if (alarm.amPm) {
setBackgroundColor(context.getColor(R.color.todays_day_color))
} else {
setBackgroundColor("YOUR COLOR")
}