'How can I change CardViews background color based on user's option in Kotlin?

I have 2 fragment pages. The first of these pages is the page where the user is given options. The other page is the page that is displayed according to the option selected by the user.

enter image description here

This page is the page where 3 options are presented to the user.

enter image description here

This page is the home page of the application. No matter which option the user clicks on the first image, they will be directed to this page. But the difference is that if he clicks on the first option in the first image, the background color of the first cardView in this image will change and the others will remain white. The same is true for other options.

For example, I have shown how the background colors of the cardViews should stop when the 3rd option is clicked. The background color should still change when the user comes to this page and clicks on a different CardView.

In short, while the active page has a background color, the background color of the inactive pages will remain white. How can I do this in fragment?



Solution 1:[1]

// CardView doesnot change its background if you want to chang the backgroung 
 then make cardview as parent layout and put view inside card view and change 
 child view backgroung color it work perfectly.(For demo try this in your xml 
 file)

  <androidx.cardview.widget.CardView 
  xmlns:android="http://schemas.android.com/apk/res/android"
  xmlns:app="http://schemas.android.com/apk/res-auto"
  android:layout_width="300dp"
  android:layout_height="600dp"
  app:cardCornerRadius="8dp"
  app:cardElevation="8dp"
  app:cardMaxElevation="4dp"
  android:layout_gravity="center_horizontal"
  app:cardUseCompatPadding="true">

  <LinearLayout
  android:layout_width="match_parent"
  android:layout_height="match_parent"
  android:background="@color/black"/>

 </androidx.cardview.widget.CardView>

 //The outcome

enter image description here

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Dhruv Sakariya