我在静态函数findViewById
中发现错误。
我的职能是 -
public static void onYearSelect() {
Spinner yearSelector;
String yearName;
yearSelector = (Spinner) findViewById(R.id.year_submit);
yearName = yearSelector.getSelectedItem().toString();
}
有没有办法解决这个错误!
我可以将yearName中的Spinner值存储为String
答案 0 :(得分:4)
您需要在函数内添加视图作为参数。
public static void onYearSelect(View view) {
Spinner yearSelector;
yearSelector = (Spinner) view.findViewById(R.id.year_submit);
yearName = yearSelector.getSelectedItem().toString();
}
The view which contains your layout data
。
当您调用该函数时,在
onYearSelect(rootView)
添加rootView
具有布局视图。
编辑1:
这是什么视图?
A View in Android is a widget that displays something. Buttons, listviews, imageviews, etc. are all subclasses of View. When you say "change view" I assume you mean change the layout by using setContentView(). This usually only needs to be done once per activity. An Activity is basically what you are referring to as a screen.
您可以阅读更多here。
答案 1 :(得分:0)
在spinner对象上设置setOnItemSelectedListener,在onItemSelected()内设置yearName的值。如下所示,
yearSelector.setOnItemSelectedListener(new OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) {
String yearName = parentView.getItemAtPosition(position).toString()
}
@Override
public void onNothingSelected(AdapterView<?> parentView) {
// your code here
}});