我试图将资源字符串名称附加到表达式,但无法继续。我的代码如下:错误具体发生在 createFromResource
方法的参数 R.array.+ previousDigitsIdentifier
中。有什么解决办法吗?
public void createPrecedingDigitsSpinner(String selectedCountry){
String selectedCntry =selectedCountry.toLowerCase();
/**confirm that value of this
* country exist in countries.xml**/
ArrayAdapter<CharSequence> adapter;
String precedingDigitsIdentifier = selectedCntry + "_preceding_digits";
try{
ArrayAdapter.createFromResource(getActivity(),*R.array.+ precedingDigitsIdentifier*,
android.R.layout.simple_spinner_item);
}catch (Resources.NotFoundException e){
CharSequence text = "the selected country contains no preceding digits data try another time";
Toast toast = Toast.makeText(context, text, duration);
toast.show();
}
}
最佳答案
您不能连接变量名称并期望它起作用。相反,您需要使用不同的方法:
ArrayAdapter.createFromResource(getActivity(),
getResources().getIdentifier(precedingDigitsIdentifier, "drawable", getPackageName()),
android.R.layout.simple_spinner_item);
这将通过查找而不是使用 Java 标识符来获取资源 ID,这允许您使用作为串联结果的字符串。
关于java - android 将字符串值名称连接到表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30986093/