I have created a singleton class where I have written 'n' number of key-value pairs, in which the values are Pair like below. My issue is, when I initially open this fragment, it displays 4 different key-value like below When I open my fragment first time
When I click the shuffle button again, it doesn't display random image and words but it only change the positions of images and the words that were shown first time when I had opened the fragment. It shows like this On clicking the button it shows like this
And then when I click again, the positions of image and names change again but the names and images don't get displayed from random pairs of singleton class but the original 4 pairs that were displayed when I had opened the Fragment like this On clicking the button 2nd time
Below is the code
- The object class
object ImageStore {
val imagesNamesMap = hashMapOf(
R.drawable.africa to Pair("Africa","Afrika"),
R.drawable.asia to Pair("Asia","Azija"),
R.drawable.europe to Pair("Europe","Europa"),
R.drawable.antartica to Pair("Antarctica","Antarktida"),
R.drawable.airplane to Pair("Aeroplane","Lėktuvas"),
R.drawable.apple1 to Pair("Apple","Obuolys"),
R.drawable.key to Pair("Key","raktas"),
R.drawable.sleep to Pair("to sleep","miegoti"),
R.drawable.shopping to Pair("to shop","apsipirkti"),
R.drawable.cinemascreen to Pair("to watch a movie","Žiūrėti filmą"),
R.drawable.goshopping to Pair("I go shopping","aš einu apsipirkti"),
R.drawable.what1 to Pair("What is it?","Kas tai?"),
R.drawable.japanesefood to Pair("Japanese food","Japonų maistas"),
R.drawable.hotcoffee to Pair("hot coffee","karšta kava"),
R.drawable.eat to Pair("to eat","valgyti"),
R.drawable.ofcourse to Pair("Of course","Žinoma"),
R.drawable.rice to Pair("rice","ryžiai"),
R.drawable.soup1 to Pair("soup","sriuba"),
R.drawable.bread1 to Pair("Bread","Duona"),
R.drawable.water1 to Pair("water","vanduo"),
R.drawable.glass1 to Pair("a glass","stiklinė"),
R.drawable.apple1 to Pair("apple","obuolys"),
R.drawable.cost to Pair("to cost","kainuoti"),
R.drawable.parents1 to Pair("parents","tėvai"),
R.drawable.classmate to Pair("classmate","klasiokas"),
R.drawable.friends1 to Pair("my friends","Mano draugai"),
R.drawable.little to Pair("a little","šiek tiek"),
R.drawable.go to Pair("Let's go","eikime!"),
R.drawable.more to Pair("more","daugiau"),
R.drawable.hand to Pair("hand","ranka"),
R.drawable.stopsign to Pair("to stop","nustoti"),
R.drawable.march to Pair("March","Kovas"),
R.drawable.february to Pair("February","Vasaris"),
R.drawable.january to Pair("January","Sausis"),
R.drawable.saturday to Pair("Saturday","Šeštadienis"),
R.drawable.friday to Pair("Friday","penktadienis"),
R.drawable.thursday to Pair("Thursday","Ketvirtadienis"),
R.drawable.wednesday to Pair("Wednesday","Trečiadienis"),
R.drawable.tuesday to Pair("Tuesday","Antradienis"),
R.drawable.monday to Pair("Monday","Pirmadienis"),
R.drawable.sunday to Pair("Sunday","Sekmadienis"),
R.drawable.autumn to Pair("autumn","ruduo"),
R.drawable.summer to Pair("Summer","vasara"),
R.drawable.spring to Pair("Spring","pavasaris"),
R.drawable.december to Pair("December","Gruodis"),
R.drawable.november to Pair("November","lapkritis"),
R.drawable.october to Pair("October","Spalis"),
R.drawable.september to Pair("September","Rugsėjis"),
R.drawable.august to Pair("August","Rugpjūtis"),
R.drawable.july to Pair("July","Liepa"),
R.drawable.june to Pair("June","Birželis"),
R.drawable.may to Pair("May","Gegužė"),
R.drawable.april to Pair("April","Balandis"),
R.drawable.march to Pair("March","Kovas"),
R.drawable.noon to Pair("Noon","vidurdienis"),
R.drawable.morning to Pair("Morning","rytas"),
R.drawable.evening to Pair("evening","vakaras"),
R.drawable.beforesleep to Pair("before sleep","prieš miegą"),
R.drawable.halfaday to Pair("half a day","pusę dienos"),
R.drawable.midnight to Pair("Midnight","vidurnaktis"),
R.drawable.decade to Pair("decade","dešimtmetį"),
R.drawable.season to Pair("Season","sezonas"),
R.drawable.year to Pair("Year","metai"),
R.drawable.month to Pair("Month","Mėnuo"),
R.drawable.day to Pair("day","diena"),
R.drawable.winter to Pair("winter","žiema"),
R.drawable.key to Pair("period","laikotarpį"),
R.drawable.workday to Pair("workday","darbo diena"),
R.drawable.weekend to Pair("weekend","savaitgalis"),
R.drawable.twice to Pair("twice","du kartus"),
R.drawable.once to Pair("once","vieną kartą"),
R.drawable.week to Pair("week","savaitė"),
R.drawable.tomorrow to Pair("tomorrow","rytoj"),
R.drawable.today to Pair("Today","šiandien"),
R.drawable.inafternoon to Pair("in the afternoon","po pietų"),
R.drawable.early to Pair("early","anksti"),
R.drawable.late to Pair("late","vėlai"),
).toList().shuffled().take(4).toMap()
}
I want any 4 elements to be displayed randomly everytime I click on the button, the button is in the Fragment PractiseFragment.kt like shown below
class PractiseFragment : Fragment() {
lateinit var binding: FragmentPractiseBinding
lateinit var practiseAdapter: PractiseAdapter
lateinit var recyclerViewPractise: RecyclerView
@SuppressLint("ClickableViewAccessibility")
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View {
// Inflate the layout for this fragment
binding = FragmentPractiseBinding.inflate(layoutInflater,container,false)
recyclerViewPractise = binding.recyclerViewPractise
val layoutManager = LinearLayoutManager(requireContext(),LinearLayoutManager.VERTICAL,false)
binding.recyclerViewPractise.layoutManager = layoutManager
// Shuffle the list of image names
//val shuffledImageNames = ImageStore.imagesNamesMap.values.toList().shuffleList()
val shuffledImageResources = ImageStore.imagesNamesMap.keys.toList().shuffleList()
val shuffledImageNames1: List<Pair<String, String>> = shuffledImageResources.mapNotNull { it ->
val pair = ImageStore.imagesNamesMap[it]
pair?.let { Pair(pair.first,pair.second)}
}.toList().shuffleList()
practiseAdapter = PractiseAdapter(shuffledImageResources.toMutableList(),
shuffledImageNames1.toMutableList(),binding.btnShuffle,recyclerViewPractise)
binding.recyclerViewPractise.adapter = practiseAdapter
practiseAdapter.initsetRecyclerView(recyclerViewPractise)
return binding.root
}
}
Below is the layout file of the PractiseFragment
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@drawable/background_color"
xmlns:tools="http://schemas.android.com/tools">
<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" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:gravity="center"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textStyle="bold"
android:gravity="center"
android:layout_marginStart="100dp"
android:text="@string/select_correct_pair" />
<ImageView
android:id="@+id/imageCat"
android:layout_width="48dp"
android:layout_height="48dp"
android:layout_marginStart="50dp"
android:src="@drawable/cat1" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/zero1"
android:textSize="16sp"
android:textColor="@color/white"
android:layout_margin="10dp" />
</LinearLayout>
<LinearLayout
android:layout_marginTop="40dp"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/linearRecyclerview"
android:orientation="vertical">
<!-- 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_marginLeft="10dp"
android:layout_marginRight="10dp"
android:layout_height="match_parent"
android:layout_marginTop="20dp"
android:orientation="vertical"
android:padding="16dp" />
</LinearLayout>
<androidx.appcompat.widget.AppCompatButton
android:layout_width="120dp"
android:layout_marginTop="10dp"
android:text="@string/shuffle"
android:id="@+id/btnShuffle"
android:textColor="#FFFF"
android:background="@drawable/orangeractangle"
android:layout_marginBottom="40dp"
android:layout_height="50dp"
android:layout_below="@id/linearRecyclerview"
android:gravity="center"
android:layout_centerHorizontal="true" />
</RelativeLayout>
Below is the code for item_practise_cards.xml file
<GridLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:columnCount="2"
android:rowCount="4"
android:layout_marginTop="10dp"
android:orientation="horizontal"
android:padding="8dp">
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:weightSum="1">
<androidx.cardview.widget.CardView
android:id="@+id/cardImagePractise"
android:layout_width="120dp"
android:layout_height="120dp"
android:layout_gravity="center"
android:layout_marginStart="30dp"
app:cardCornerRadius="10dp"
android:foreground="?android:attr/selectableItemBackground">
<ImageView
android:id="@+id/imageViewPractise"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:scaleType="fitCenter" />
</androidx.cardview.widget.CardView>
<androidx.cardview.widget.CardView
android:id="@+id/cardTextPractise"
android:layout_width="120dp"
android:layout_height="120dp"
android:layout_gravity="center"
android:layout_marginStart="30dp"
android:layout_marginEnd="20dp"
app:cardCornerRadius="10dp"
android:foreground="?android:attr/selectableItemBackground">
<TextView
android:id="@+id/textViewPractise"
android:layout_width="wrap_content"
android:gravity="center"
android:layout_height="wrap_content"
android:textStyle="bold"
android:layout_gravity="center"
android:text="Random Name"
android:textSize="12sp" />
<TextView
android:layout_marginTop="20dp"
android:id="@+id/textViewPractise1"
android:layout_width="wrap_content"
android:gravity="center"
android:layout_height="wrap_content"
android:textStyle="bold"
android:layout_gravity="center"
android:text="Random Name"
android:textSize="12sp" />
</androidx.cardview.widget.CardView>
</LinearLayout>
</GridLayout>
Below is the code of my Adapter class PractiseAdapter.kt
class PractiseAdapter(
private var imageResources: MutableList<Int>,
private var imageNames1: MutableList<Pair<String,String>>,
btnShuffle: AppCompatButton,
recyclerViewPractise: RecyclerView,
) : RecyclerView.Adapter<PractiseAdapter.PractiseViewHolder>() {
lateinit var recyclerView: RecyclerView
private var anyCardIsGreen = false
private var selectedImageResource = -1
private var selectedImageName = ""
private var previousSelectedImageResource = -1
private var previousSelectedImageName = ""
init {
btnShuffle.setOnClickListener {
shuffleCards()
}
}
private fun shuffleCards() {
// Shuffle the card data (images and names)
imageResources.shuffle()
imageNames1.shuffle()
// Reset the selected image and name
selectedImageResource = -1
selectedImageName = ""
previousSelectedImageResource = -1
previousSelectedImageName = ""
// Reset the background color of cardImage views to white
resetCardImageBackgroundToWhite()
notifyDataSetChanged()
}
fun initsetRecyclerView(recyclerView: RecyclerView) {
this.recyclerView = recyclerView
}
private fun resetCardImageBackgroundToWhite() {
// Iterate through the card views and reset the background color of cardImage to white
for (position in 0 until imageResources.size) {
val holder = recyclerView.findViewHolderForAdapterPosition(position) as? PractiseViewHolder
holder?.cardImagePractise?.setCardBackgroundColor(Color.WHITE)
}
}
companion object {
val GREEN_COLOR = Color.parseColor("#ABEBC6")
}
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 = imageResources.size
override fun onBindViewHolder(holder: PractiseViewHolder, position: Int) {
val imageResource = imageResources[position]
val imageName1 = imageNames1[position]
holder.imageViewPractise.setImageResource(imageResource)
holder.textViewPractise.text = imageName1.first
holder.textViewPractise1.text = imageName1.second
holder.cardImagePractise.setOnClickListener {
selectedImageResource = imageResource
previousSelectedImageResource = selectedImageResource
selectedImageName = ""
notifyDataSetChanged()
holder.cardImagePractise.setCardBackgroundColor(GREEN_COLOR)
}
holder.cardTextPractise.setOnClickListener {
if (selectedImageResource == -1) {
Toast.makeText(
it.context,
"Please select an image card first.",
Toast.LENGTH_SHORT
).show()
} else {
selectedImageName = imageNames1[position].first
previousSelectedImageName = selectedImageName
}
notifyDataSetChanged()
}
val nameColor = if(imageNames1[position].first ==selectedImageName){
if(ImageStore.imagesNamesMap[selectedImageResource]?.first==selectedImageName){
Toast.makeText(
holder.itemView.context,
"Correct name selected!",
Toast.LENGTH_SHORT
).show()
anyCardIsGreen=true
holder.cardTextPractise.setBackgroundColor(GREEN_COLOR) // Set green background for the name card
Color.GREEN
} else {
Toast.makeText(
holder.itemView.context,
"Wrong name selected!",
Toast.LENGTH_SHORT
).show()
Color.RED
}
} else {
holder.cardTextPractise.setBackgroundColor(Color.WHITE)
Color.WHITE
}
holder.cardTextPractise.setBackgroundColor(nameColor)
// Check if the card is green and set anyCardIsGreen accordingly
}
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)
val textViewPractise1: TextView = itemView.findViewById(R.id.textViewPractise1)
}
}
In short, I want to display random key-value pairs from the object class everytime I click on button and not just display the same original 4 pairs that were displayed when I had opened my Fragment for first time.
Change your
ImageStoreobject to thisChange
shuffleCards()ofPractiseAdapterto this