我有一个带有各种项目的微调器,用于从所选项目中获取文本。
我想使用此文本为openRawResource准备资源ID,我的代码看起来像
Spinner spinner = (Spinner) v.findViewById(R.id.accident);
String text = spinner.getSelectedItem().toString();
String newt = "R.raw." + text;
int textxx = Integer.parseInt(newt);
InputStream is = getResources().openRawResource(textxx);
但它不起作用,任何想法
答案 0 :(得分:1)
问题出在这里
int textxx = Integer.parseInt(newt);
正确的做法是:
int resID = getResources().getIdentifier(text, "raw", getApplicationContext().getPackageName());
现在您可以使用InputStream
,如下所示:
InputStream is = getResources().openRawResource(resID);
不允许getPackageName()表示其未定义的
如果你在Activity
,你可以这样做:
this.getPackageName(); //this -> context
如果你在Fragment
,你可以这样做:
getActivity().getPackageName();
但仅在我选择其他项目时打开微调器中的第一项不打开其他文件
您需要实施onItemSelected()
,请参阅以下代码。
final Spinner sp = (Spinner)findViewById(R.id.spinner);
sp.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) {
// your code here
String text = sp.getSelectedItem().toString();
int resID = getResources().getIdentifier(text, "raw", getPackageName());
InputStream is = getResources().openRawResource(resID);
Toast.makeText(MainActivity.this, "Clicked", Toast.LENGTH_SHORT).show();
}
@Override
public void onNothingSelected(AdapterView<?> parentView) {
// your code here
}
});
答案 1 :(得分:0)
试试这个 将其添加到strings.xml:
<string-array name="raw_resources">
<item>@raw/yourresource1</item>
<item>@raw/yourresource2</item>
<item>@raw/yourresource3</item>
<item>@raw/yourresource4</item>
<item>@raw/yourresource5</item>
</string-array>
现在在您的片段中访问它:
final TypedArray resourceIDS = res.obtainTypedArray(R.array.select_sounds);
int[] resIds = new int[sounds.length()];
for (int i = 0; i < sounds.length(); i++) {
resIds[i] = sounds.getResourceId(i, -1);
}
resourceIDS.recycle();
现在,您拥有resIds数组中原始文件ID的所有ID。只需根据微调器中选择的项目对其进行索引。
答案 2 :(得分:0)
第一个想法是使用HashMap查找所需值的ResID。但是,这有一个问题,即&#39; String&#39;需要是唯一的,否则你可能会遇到一些非常糟糕的行为(当你填满hashmap时条目会互相覆盖)
但Resources has a method为您执行此查找
/*
Return a resource identifier for the given resource name.
A fully qualified resource name is of the form "package:type/entry". The
first two components (package and type) are optional if defType and
defPackage, respectively, are specified here.
Note: use of this function is discouraged. It is much more efficient to
retrieve resources by identifier than by name.
*/
public int getIdentifier (String name, String defType, String defPackage)
所以试试这个:
Spinner spinner = (Spinner) v.findViewById(R.id.accident);
String resName = spinner.getSelectedItem().toString();
int resID= this.getResources().getIdentifier(
resName, "raw", this.getPackageName());
InputStream is = getResources().openRawResource(resID);