SetAdapter在Fragment for Spinner中崩溃了Android Studio

时间:2018-08-16 01:37:26

标签: android android-fragments fragment spinner

当我注释掉setAdapter行时,该程序不会崩溃。

public void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

final Spinner mySpinner = getActivity().findViewById(R.id.mySpinner);

ArrayAdapter adapter = ArrayAdapter.createFromResource(this.getActivity(), R.array.spinnerArray, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
mySpinner.setAdapter(adapter);

}
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.input_personal_data_fragment, container, false);

    return view;
}

我尝试使用new ArrayAdapter代替createFromResource,但是那也不起作用。而且我已经将所有内容放入OnCreateView方法中,所以这无济于事。我知道我丢失了一些东西,我在MainActivity中尝试了一下,效果很好。

2 个答案:

答案 0 :(得分:0)

因为使用onCreateView时必须在fragment中增加布局,然后对要从findViewById返回的视图引用执行onCreateView

答案 1 :(得分:0)

尝试一下:

问题在于您是否没有扩大视图

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle 
savedInstanceState) {
View v = inflater.inflate(R.layout.manual, container, false);

String [] values = 
    {"demo1","demo2","demo3","demo4","demo5"};
Spinner spinner = (Spinner) v.findViewById(R.id.spinner1);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this.getActivity(), android.R.layout.simple_spinner_item, values);
adapter.setDropDownViewResource(android.R.layout.simple_dropdown_item_1line);
spinner.setAdapter(adapter);

return v;

}

它可以帮助您。