sleepy
sleepy

Reputation: 193

How to make variable from an array

I'm using an array like below and I'm using "category" variable after that without problem.

var category = resources.getStringArray(R.array.**main_menu**)

My question is, how can I make a variable "main_menu"? There are other arrays also exist and I want to send their names as a varible in this line?

I tried the code below, but surely it's not working, because it's text and "getStringArray" expecting Int.

var **text** = R.array.main_menu
var mainCategory = resources.getStringArray(**text**)

Upvotes: 0

Views: 57

Answers (1)

Natig Babayev
Natig Babayev

Reputation: 3296

By using getIdentifier() method, you can get the integer id of your resource. That method accepts three parameters:

  • Name of the resource as string

  • Type of the resource, which is in your case "array"

  • Package name

By using the resource id returned from resources.getIdentifier(arrayName, "array", getPackageName()), you can get array.

Here is full code:

var arrayName = "main_menu"
val resId = resources.getIdentifier(arrayName, "array", context.packageName)
var mainCategory = resources.getStringArray(resId)

Upvotes: 2

Related Questions