dimanche 7 juin 2020

Display random string from Array stored in values/ with Kotlin?

I searched for a way to display in my TextView a random string from my array list stored in Values/Rarity.xml.

There are many examples here all in Java, but none are working.

I tried: kotlin Get random string from array (can't make it work with an array from my values/rarity.xml)

Getting random values from an ArrayList

I am new to Android studio and would like to know how to make it work, has I've been trying for the past few hours without success.

This is what I would like to achieve, but the app crash when I click on the button :

package com.example.myapplication

import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import kotlinx.android.synthetic.main.activity_main.*

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        val rarity = arrayOf(R.array.wp_rarity)
        val randomRarity = rarity.random()

        btn_generate.setOnClickListener {
            item_type.setText(randomRarity)
        }
    }
}

If I replace the val rarity = arrayOf(R.array.wp_rarity) by val rarity = arrayOf("test", "test2") it does work but I would like to use my arrays in values/*.xml in order to optimize it. Or is there another way ?

Regards,




Aucun commentaire:

Enregistrer un commentaire