android setText with getString using variable name

2019-07-28 02:01发布

So, searching the internet I found many examples that were not what I need...

Here is my situation:

Imagine that you have a resource that is an array called songs and many 's with each song name..so, imagina you have like 200 song names displayed on a listview..

when you click a song, the app loads another activity with the lyrics for that song... but HOW do you do that?

Here is how I did it.. I passed the name of the song to this new activity, loaded the resource where the lyrics are...

BUT, at the time I have to setText with the lyrics, I got a problem... should I do a switch with 200 cases? that sounds insane, so, what I did was, I used the same name of the song to the lyrics..so it should load like this:

TextView txtProduct = (TextView) findViewById(R.id.product_label);

    Intent i = getIntent();
    // getting attached intent data
    String[] musicas = getResources().getStringArray(R.array.botafogo_songs);
    // this here is where it brings the name of the music to the activity
    String product = i.getStringExtra("product");
    // displaying selected product name
    if (Arrays.asList(musicas).contains(product)) {
            //just formating so they have the same name.
        String productSplit = product.split("- ")[1];
        productSplit.replace(" ", "");
        txtProduct.setText(getString(R.string.AbreAlas)); 
    }else{
        txtProduct.setText("não contem");
    }

Ok, AbreAlas is the name of my resource..it loads fine.. BUT, I cant leave it like this...it should be a variable name... like: R.string.+productSplit or something like this..

I can't find the solution nowhere..

1条回答
我欲成王,谁敢阻挡
2楼-- · 2019-07-28 02:34

You can use getIdentifier():

int resourceName = getResources().getIdentifier(productSplit, "string", getPackageName());

And then:

txtProduct.setText(getString(resourceName));

Don't forget to wrap that in a try and catch.

查看更多
登录 后发表回答