Why background of wrong name cardview selected doesn't change into Red in android?

38 Views Asked by At

I have two columns in which All images (as keys) are in first column and all the names (values) are in second column. The names are displayed randomly and user needs find the correct name for image and click. so when the user click the right name, the background of that name card will turn into Green and Red if wrong name card is selected. But at the moment even if I select wrong name card, still the background chnages to green and not to Red like this This is how it looks , the name card colout should be red as I have choosen wrong name

Following is the code of my Fragment practiseFragment.kt

    package com.example.visuallithuanian.ui.activities.fragments
    
    import android.os.Bundle
    import androidx.fragment.app.Fragment
    import android.view.LayoutInflater
    import android.view.MenuItem
    import android.view.View
    import android.view.ViewGroup
    import android.widget.Toast
    import androidx.appcompat.app.AppCompatActivity
    import androidx.appcompat.widget.Toolbar
    import androidx.navigation.fragment.findNavController
    import androidx.recyclerview.widget.GridLayoutManager
    import androidx.recyclerview.widget.LinearLayoutManager
    import androidx.recyclerview.widget.RecyclerView
    import com.example.visuallithuanian.R
    import com.example.visuallithuanian.adapter.PractiseAdapter
    import com.example.visuallithuanian.databinding.FragmentPractiseBinding
    import dagger.hilt.android.AndroidEntryPoint
    class PractiseFragment : Fragment() {
        lateinit var binding: FragmentPractiseBinding
        lateinit var recyclerView: RecyclerView
        private val imageNamesMap= HashMap<Int,String>()
    
        override fun onCreateView(
            inflater: LayoutInflater, container: ViewGroup?,
            savedInstanceState: Bundle?
        ): View {
            // Inflate the layout for this fragment
    
            binding = FragmentPractiseBinding.inflate(layoutInflater,container,false)
    
            binding.backIcon.setOnClickListener {
                findNavController().navigate(R.id.action_practiseFragment_to_userFragment)
            }
    
            populateImages()
    
            binding.recyclerViewPractise.layoutManager = LinearLayoutManager(requireContext(),LinearLayoutManager.VERTICAL,false)
            binding.recyclerViewPractise.adapter = PractiseAdapter(imageNamesMap)
    
    
            return binding.root
    
        }
    
        private fun populateImages() {
            // Add image resources to a list
            val imageResources = listOf(
                R.drawable.africa,
                R.drawable.asia,
                R.drawable.europe,
                R.drawable.antartica,
                // Add more image resources as needed
            )
    
            // Add image names to a list in random order
            val imageNames = listOf(
                "Africa",
                "Asia",
                "Europe",
                "Antarctica",
                // Add more image names corresponding to the resources
            ).shuffled()
    
            // Use the shuffled names to assign each image resource ID a corresponding name in the imageNamesMap
            for (i in imageResources.indices) {
                imageNamesMap[imageResources[i]] = imageNames[i]
            }
        }
    
    
        @Deprecated("Deprecated in Java")
        override fun onOptionsItemSelected(item: MenuItem): Boolean {
            when(item.itemId){
    
                android.R.id.home->{
                    requireActivity().onBackPressed()
                    return true
                }
            }
            return super.onOptionsItemSelected(item)
        }
    
    
    }

Following is the code of my Adapter class **PractiseAdapter.kt**

package com.example.visuallithuanian.adapter

import android.annotation.SuppressLint
import android.graphics.Color
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import android.widget.Toast
import androidx.cardview.widget.CardView
import androidx.recyclerview.widget.RecyclerView
import com.example.visuallithuanian.R

class PractiseAdapter(private val imageNamesMap: HashMap<Int, String>) :
    RecyclerView.Adapter<PractiseAdapter.PractiseViewHolder>() {

    private val imagesList: MutableList<Int> = imageNamesMap.keys.toMutableList()

    // Store the positions and names of the selected image and name cards
    private var selectedImagePosition = -1
    private var selectedNamePosition = -1
    private var correctName = ""

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): PractiseViewHolder {
        val view =
            LayoutInflater.from(parent.context).inflate(R.layout.item_practise_cards, parent, false)
        return PractiseViewHolder(view)
    }

    override fun getItemCount(): Int = imagesList.size

    override fun onBindViewHolder(holder: PractiseViewHolder, @SuppressLint("RecyclerView") position: Int) {
        val imageResource = imagesList[position]
        val imageName = imageNamesMap[imageResource]

        holder.imageViewPractise.setImageResource(imageResource)
        holder.textViewPractise.text = imageName

        // Set the background color of the image card based on selection
        holder.cardImagePractise.setCardBackgroundColor(
            if (selectedImagePosition == position) Color.GREEN else Color.LTGRAY
        )

        // Set the background color of the name card based on selection and correctness
        holder.cardTextPractise.setCardBackgroundColor(
            when {
                selectedNamePosition == position && getImageName(selectedNamePosition) == correctName -> Color.GREEN // Correct name selected together with the image
                selectedNamePosition == position -> Color.RED // Wrong name selected independently
                else -> Color.LTGRAY // Default color
            }
        )

        holder.cardImagePractise.setOnClickListener {
            // Set the selected image position and reset selected name position
            selectedImagePosition = position
            selectedNamePosition = -1
            correctName = ""
            notifyDataSetChanged()
        }

        holder.cardTextPractise.setOnClickListener {
            if (selectedImagePosition != -1) {
                // Set the selected name position and the correct name
                selectedNamePosition = position
                correctName = getImageName(selectedNamePosition)
                notifyDataSetChanged()
            } else {
                Toast.makeText(
                    it.context,
                    "Please select an image card first.",
                    Toast.LENGTH_SHORT
                ).show()
            }
        }
    }

    private fun getImageName(position: Int): String {
        return if (position in 0 until imagesList.size) {
            imageNamesMap[imagesList[position]] ?: ""
        } else {
            ""
        }
    }

    class PractiseViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        val cardImagePractise: CardView = itemView.findViewById(R.id.cardImagePractise)
        val cardTextPractise: CardView = itemView.findViewById(R.id.cardTextPractise)
        val imageViewPractise: ImageView = itemView.findViewById(R.id.imageViewPractise)
        val textViewPractise: TextView = itemView.findViewById(R.id.textViewPractise)
    }
}

This is the fragment layout fragment_practise.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    xmlns:tools="http://schemas.android.com/tools">
    <androidx.appcompat.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="100dp"
        android:background="@drawable/flash_tablebar"
        android:elevation="4dp"
        android:theme="@style/ThemeOverlay.AppCompat.ActionBar"
        android:layout_alignParentTop="true">


        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal">
            <ImageView
                android:id="@+id/back_icon"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginTop="20dp"
                android:layout_marginStart="10dp"
                android:src="@drawable/ic_arrow_back" />
            <ImageView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:id="@+id/imageDiamonds"
                android:layout_below="@id/toolbar"
                android:src="@drawable/diamond" />
        </LinearLayout>


    </androidx.appcompat.widget.Toolbar>



    <!-- RecyclerView to display the image cards -->
    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/recyclerViewPractise"
        android:layout_width="match_parent"
        tools:listitem="@layout/item_practise_cards"
        android:layout_marginTop="100dp"
        android:layout_height="match_parent"
        android:orientation="vertical"
        android:padding="16dp" />

</RelativeLayout>

this is the layout file of Adapter class, item_practise_cards

<GridLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:columnCount="2"
    android:orientation="horizontal"
    android:padding="8dp">

    <androidx.cardview.widget.CardView
        android:id="@+id/cardImagePractise"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout_margin="4dp"
        android:onClick="onCardClick"
        android:clickable="true"
        android:foreground="?android:attr/selectableItemBackground">

        <ImageView
            android:id="@+id/imageViewPractise"
            android:layout_width="150dp"
            android:layout_height="150dp"
            android:scaleType="centerCrop" />
    </androidx.cardview.widget.CardView>

    <androidx.cardview.widget.CardView
        android:id="@+id/cardTextPractise"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout_margin="4dp"
        android:onClick="onCardClick"
        android:clickable="true"
        android:foreground="?android:attr/selectableItemBackground">

        <TextView
            android:id="@+id/textViewPractise"
            android:layout_width="150dp"
            android:gravity="center"
            android:layout_height="150dp"
            android:textStyle="bold"
            android:text="Random Name"
            android:textSize="18sp" />
    </androidx.cardview.widget.CardView>
</GridLayout>

I just want the background of name card that I click to be turned to Red if its a wrong name

0

There are 0 best solutions below