带有setString的android setText使用变量名 [英] android setText with getString using variable name
问题描述
因此,在互联网上搜索时,我发现了很多我不需要的示例...
So, searching the internet I found many examples that were not what I need...
这是我的情况:
假设您有一个资源,该资源是一个名为Songs的数组,并且每个歌曲的名称都有很多..因此,想象中您在列表视图中显示的歌曲名约为200个.
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...
但是,当我必须用歌词设置setText时,我遇到了问题...我应该切换200个案例吗?听起来很疯狂,所以我所做的是,我在歌词中使用了与歌曲相同的名称..因此它应该像这样加载:
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");
}
好的,AbreAlas是我的资源的名称.
但是,我不能这样保留它.它应该是一个变量名.
像:R.string.+productSplit
或类似的东西.
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..
我找不到解决方案.
推荐答案
您可以使用getIdentifier()
:
int resourceName = getResources().getIdentifier(productSplit, "string", getPackageName());
然后:
txtProduct.setText(getString(resourceName));
别忘了将它包装起来,一目了然.
Don't forget to wrap that in a try and catch.
这篇关于带有setString的android setText使用变量名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!