Android dynamic String Resources

匿名 (未验证) 提交于 2019-12-03 01:57:01

问题:

in my app I do a web request that returns some result code, e.g. 105. I have string resources that look like that

O.K.Something went wrong.Fatal error.

Now I want to do something like that

Toast.makeText(parent.getApplicationContext(),         parent.getString(R.string.r+resultCode), Toast.LENGTH_LONG).show(); 

while r+resultCode is the resource identifier.

This does not work. Any idea how to do that?

回答1:

Try this getResources().getIdentifier(name, defType, defPackage) in a simple way.

Toast.makeText(this, getResources().getIdentifier("r"+resultcode, "string",  getPackageName()), Toast.LENGTH_LONG).show(); 


回答2:

You can do it using getResources().getIdentifier(name, defType, defPackage). Something like this:

// Assuming resultCode is an int, use %s for String int id = getResources().getIdentifier(String.format("r%d", resultCode),                                        "string", getPackageName()); String result = getString(id); 


回答3:

Try as below, its working for me. Use parent.getApplicationContext() for you.

String str = getString(R.string.r)+resultCode;          Toast.makeText(getApplicationContext(),                 str, Toast.LENGTH_LONG).show(); 


回答4:

A simple way to getting resource ID from string. Here resourceName is the name of resource ImageView in drawable folder which is included in XML file as well.Im getting "id" you can use "string".

int resID = getResources().getIdentifier(resourceName, "id", getPackageName()); ImageView im = (ImageView) findViewById(resID); Context context = im.getContext(); int id = context.getResources().getIdentifier(resourceName, "drawable", context.getPackageName()); im.setImageResource(id); 


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!