0

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**)
7
  • So, you want to get string array by name of it? Commented Sep 19, 2019 at 18:57
  • Yes, there are 10 other arrays exist, so I want to send these arrays to this line. Commented Sep 19, 2019 at 19:00
  • Ok, according to my understanding, I put answer. You can check out. Commented Sep 19, 2019 at 19:00
  • 1
    You can try context.getPackageName(). You can use same context which you use to get resources. Commented Sep 19, 2019 at 19:58
  • 1
    That also worked, thanks again! Commented Sep 19, 2019 at 20:08

1 Answer 1

2

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)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.