这很简单。我只想在不使用。Strings
且不使用Spinner
文件夹的情况下将xml
添加到Resources
。
我使用了onCreateOptionsMenu(Menu menu)
,但我找不到解决问题的方法。
我见过 How can I add items to a spinner in Android? ,但在我的情况下它不起作用......
这是我的代码:
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.action_bar3, menu);
setTitle("");
String[] arraySpinner = new String[] {
"1", "2", "3", "4", "5"
};
Spinner s = (Spinner) findViewById(R.id.spinner);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,R.array.spinner_values);
s.setAdapter(adapter);
return true;
}
注意:这段代码没有运行,因为我需要一种布局,但我不知道布局是什么......
答案 0 :(得分:1)
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, arraySpinner);
崩溃:java.lang.NullPointerException:尝试调用虚拟 方法Line:s.setAdapter(adapter);
在onCreate
方法内初始化它们,而不是在onCreateOptionsMenu
public class SpinnerExample extends Activity {
private String[] arraySpinner;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
this.arraySpinner = new String[] {
"1", "2", "3", "4", "5"
};
Spinner s = (Spinner) findViewById(R.id.spinner);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, arraySpinner);
s.setAdapter(adapter);
}
}
答案 1 :(得分:0)
您可以像这样创建一个数组适配器:
ArrayAdapter aa = new
ArrayAdapter(this, android.R.layout.simple_spinner_item, arraySpinner);
答案 2 :(得分:0)
String categoryItem1 = "item1";
String categoryItem2 = "item2";
String categoryItem3 = "item3";
List<String> categories = new ArrayList<String>();
categories.add(categoryItem1);
categories.add(categoryItem2);
categories.add(categoryItem3);
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(getActivity(), R.layout.spinnner_item, categories);
// attaching data adapter to spinner
spinner.setAdapter(dataAdapter);
答案 3 :(得分:0)
对于任何寻求Kotlin方法的人:
private fun setUpTranslateToSpinner() {
val languages = listOf(
"English",
"German",
"Russian",
"Arabic",
"Japanese",
"Chinese"
).sorted()
ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, languages).apply {
setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
translateToSpinner.adapter = this
}
translateToSpinner.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) {
val item = parent?.getItemAtPosition(position)
item.let { Log.e(TAG, item.toString()) }
}
override fun onNothingSelected(parent: AdapterView<*>?) {
}
}
}