我有一个主要活动,由spinner + 3个片段(标签)组成。我想从片段访问微调器值。所以我将这段代码写入我片段中的onActivityCreated
:
final Spinner spinner = (Spinner) getView().findViewById(R.id.spinnerOblasti);
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) {
/*TextView[] vystrahy = new TextView[1];
vystrahy[0] = (TextView) getView().findViewById(R.id.txtVystrahy);
(new htmlParser(vystrahy, 0) ).execute(new Integer[]{spinner.getSelectedItemPosition()});*/
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
但是当我运行我的应用程序时,spinner会抛出nullpointerexception。关于如何从片段访问它的任何想法?
这是我的onCreateView,我认为这会导致问题,但我不知道如何解决它:
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_tab1, container, false);
return rootView;
}
先谢谢
答案 0 :(得分:0)
不能那样工作,你对旋转器价值意味着什么?如果要访问微调器对象,则必须设置一个将由您的活动实现的接口,然后在onActivityCreated中,您可以调用该接口的方法来执行某些操作。例如:
public class MyClass implements MyInterface {
public interface MyInterface {
void doSomethingWithSpinner();
}
public void doSomethingWithSpinner() {
mySpinner.setVisibility(View.VISIBLE);
}
}
你的onActivityCreated:
if(getActivity() instanceof MyInterface) {
((MyInterface)getActivity()).doSomethingWithSpinner();
}