如何从kotlin中的单例类中随机选择任意4个键值对来显示在Fragment中?

问题描述 投票:0回答:1

我创建了一个单例类,在其中编写了“n”个键值对,其中的值是如下所示的 Pair 。我的问题是,当我最初打开这个片段时,它显示 4 个不同的键值,如下所示 When I open my fragment first time

当我再次单击随机播放按钮时,它不会显示随机图像和文字,而只会更改我打开片段时第一次显示的图像和文字的位置。显示是这样的On clicking the button it shows like this

然后,当我再次单击时,图像和名称的位置再次更改,但名称和图像不会从单例类的随机对中显示,而是从我打开片段时显示的原始 4 对显示,如下所示 On clicking the button 2nd time

下面是代码

  1. 对象类别
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()
    }

我希望每次点击按钮时随机显示任意 4 个元素,该按钮位于 Fragment PractiseFragment.kt 中,如下所示

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
        
            }
        
        }

下面是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>

以下是 item_practise_cards.xml 文件的代码

<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>

下面是我的适配器类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)
    
        }
    }

简而言之,我希望每次单击按钮时都显示对象类中的随机键值对,而不仅仅是显示我第一次打开 Fragment 时显示的相同的原始 4 对。

android android-recyclerview android-adapter
1个回答
0
投票

将您的

ImageStore
对象更改为此

object ImageStore {
        private val _imagesNamesMap = hashMapOf(
            R.drawable.africa to Pair("Africa","Afrika"),
            R.drawable.asia to Pair("Asia","Azija"),
            // more data
        )

        val imagesNamesMap: Map<Int, String>
          get() = _imagesNamesMap.toList().shuffled().take(4).toMap() 
    }
© www.soinside.com 2019 - 2024. All rights reserved.