如何选择Android kotlin中对象类中声明的四个hashmap键值对?

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

因此,我声明了一个对象类 ImageStore.kt ,其中声明了五个键值对。因此,我想要这些密钥对值中的 4 个,同时排除任何随机的第 5 个密钥对值。我创建了两列,其中第一列中的所有图像 [图像是键] 和第二列中的名称 [值是名称] 我还想对值进行洗牌并显示,以便用户可以找到正确的名称。下面是我的对象类 ImageStore .kt 代码。

package com.example.visuallithuanian.constants

import com.example.visuallithuanian.R

object ImageStore {

    val imagesNamesMap= hashMapOf(
        R.drawable.africa to "Africa",
        R.drawable.asia to "Asia",
        R.drawable.europe to "Europe",
        R.drawable.antartica to "Antarctica",
        R.drawable.airplane to "Airplane"
    )

    val selectedImagesNamesMap = imagesNamesMap.toList().take(4).toMap()
}

因此,例如我在这里想要的是,我将仅随机选取前四个键值对,同时避免第五个键值对。然后我将在第一列的卡片视图上显示图像,然后随机排列值并将它们显示在第二列的名称卡片视图中。但目前发生的情况是,它随机从第 5 个键值对中获取值,同时忽略大约 4 个键值对中的一个值,如下所示

因此,正如您所看到的,它将飞机显示为来自第 5 个键值对的洗牌值之一。所以,我想要前 4 个键值对中的缺失值而不是它。

下面是我的适配器类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
import com.example.visuallithuanian.constants.ImageStore


class PractiseAdapter(
    private val imageResources: List<Int>,
    private val imageNames: List<String>
) : RecyclerView.Adapter<PractiseAdapter.PractiseViewHolder>() {

    private val displayedIndexes: List<Int> = (0 until 4).shuffled()
    private val displayedImageResources = mutableListOf<Int>()
    private val displayedImageNames = mutableListOf<String>()

    private var selectedImageResource = -1
    private var selectedImageName = ""

    init {
        displayedIndexes.forEach { index ->
            displayedImageResources.add(imageResources[index])
            displayedImageNames.add(imageNames[index])
        }
    }

    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 = displayedImageResources.size

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

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

        // Set the background color of the image card based on selection
        holder.cardImagePractise.setCardBackgroundColor(
            if (selectedImageResource == imageResource) Color.GREEN else Color.WHITE
        )

        holder.cardImagePractise.setOnClickListener {
            // Set the selected image position and reset the selected name position
            selectedImageResource = imageResource
            selectedImageName = ""
            notifyDataSetChanged()
        }

        holder.cardTextPractise.setOnClickListener {
            if (selectedImageResource == -1) {
                Toast.makeText(
                    it.context,
                    "Please select an image card first.",
                    Toast.LENGTH_SHORT
                ).show()
            } else {
                selectedImageName = imageName
            }
            notifyDataSetChanged()
        }

        val nameColor = if (imageName == selectedImageName) {
            if (ImageStore.imagesNamesMap[imageResource] == selectedImageName) {
                Toast.makeText(
                    holder.itemView.context,
                    "Correct name selected!",
                    Toast.LENGTH_SHORT
                ).show()
                Color.GREEN
            } else {
                Toast.makeText(
                    holder.itemView.context,
                    "Wrong name selected!",
                    Toast.LENGTH_SHORT
                ).show()
                Color.RED
            }
        } else {
            Color.WHITE
        }

        holder.textViewPractise.setBackgroundColor(nameColor)
    }

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

下面是我的适配器类的 **[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">

    <androidx.cardview.widget.CardView
        android:id="@+id/cardImagePractise"
        android:layout_width="150dp"
        android:layout_height="120dp"
        android:layout_gravity="center"
        android:layout_margin="4dp"
        app:cardCornerRadius="10dp"
        android:foreground="?android:attr/selectableItemBackground">

        <ImageView
            android:id="@+id/imageViewPractise"
            android:layout_width="100dp"
            android:layout_marginLeft="20dp"
            android:layout_marginTop="10dp"
            android:layout_height="100dp"
            android:scaleType="centerCrop" />
    </androidx.cardview.widget.CardView>

    <androidx.cardview.widget.CardView
        android:id="@+id/cardTextPractise"
        android:layout_width="150dp"
        android:layout_height="120dp"
        android:layout_gravity="center"
        android:layout_margin="4dp"
        app:cardCornerRadius="10dp"
        android:foreground="?android:attr/selectableItemBackground"
        android:focusable="true"
        tools:ignore="UsingOnClickInXml">

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

下面是xml文件fragment_practise.xml,它是Fragment的布局文件Practise Fragment.kt

<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"
    android:background="@color/nana"
    xmlns:tools="http://schemas.android.com/tools">

    <!-- 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_marginLeft="20dp"
        android:layout_marginRight="20dp"
        android:layout_marginBottom="20dp"
        android:layout_height="match_parent"
        android:orientation="vertical"
        android:padding="16dp" />

</RelativeLayout>

下面是我的片段的代码PractiseFragment.kt

package com.example.visuallithuanian.ui.activities.fragments


import com.example.visuallithuanian.adapter.PractiseAdapter
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.LinearLayoutManager
import com.example.visuallithuanian.Utils.shuffleList
import com.example.visuallithuanian.constants.ImageStore
import com.example.visuallithuanian.databinding.FragmentPractiseBinding

class PractiseFragment : Fragment() {
    lateinit var binding: FragmentPractiseBinding

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        // Inflate the layout for this fragment

        binding = FragmentPractiseBinding.inflate(layoutInflater,container,false)


        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 adapter = PractiseAdapter(shuffledImageResources,shuffledImageNames)
        binding.recyclerViewPractise.adapter = adapter


        return binding.root

    }

}

TLDR;我随机想取任意四个键值对,然后将所取的值打乱并显示。

android kotlin android-recyclerview android-cardview
2个回答
0
投票

试试这个功能

fun getRandom4(): MutableMap<Int, String> {
    val selectedImagesNamesMap: MutableMap<Int, String> = mutableMapOf()
    val randomKeys = ImageStore.imagesNamesMap.keys.shuffled().take(4).map {
        selectedImagesNamesMap[it] = ImageStore.imagesNamesMap[it] ?: ""
    }
    val selectedValues = selectedImagesNamesMap.values.shuffled().toMutableList()
    selectedImagesNamesMap.keys.toList().forEachIndexed { index, key ->
        selectedImagesNamesMap[key] = selectedValues[index]
    }
    return selectedImagesNamesMap
}

0
投票

使用此功能并相应地修改你的功能

object ImageStore {

val imagesNamesMap = hashMapOf(
    R.drawable.africa to "Africa",
    R.drawable.asia to "Asia",
    R.drawable.europe to "Europe",
    R.drawable.antartica to "Antarctica",
    R.drawable.airplane to "Airplane"
)

val selectedImagesNamesMap: Map<Int, String> = imagesNamesMap.toList()
    .shuffled()
    .take(4)
    .toMap() }

以下是代码的作用:

imagesNamesMap 保持不变。它包含所有键值对。

selectedImagesNamesMap修改如下:

.toList() 将 imagesNamesMap 转换为键值对列表。

.shuffled() 随机打乱列表。

.take(4) 从打乱的列表中选择前四个键值对。

.toMap() 将选定的键值对转换回映射。

通过使用 .shuffled() 函数,您可以确保每次运行代码时都从 imagesNamesMap 中选择随机键值对。这种方法可以防止排除任何特定的键值对,并提供您正在寻找的随机选择。

© www.soinside.com 2019 - 2024. All rights reserved.