可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
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);