在我的微调器上创建ArrayAdapter时遇到了麻烦。我不知道如何向你解释,但人们说一张照片说1000字。所以我提供了我的问题的图片。请帮帮我,我真的不知道该怎么做。
这是我的班级
public class SettingFragment extends Fragment{
private View rootView;
Spinner spinner;
ArrayAdapter<CharSequence> adapter;
public SettingFragment(){
//required empty public constructor
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.fragment_setting, container, false);
spinner = (Spinner)rootView.findViewById(R.id.spinner);
adapter = ArrayAdapter.createFromResource(this, R.array.select_font_size, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
return rootView;
}
}
这是我的string.xml
<string-array name="select_font_size">
<item>Small</item>
<item>Default</item>
<item>Large</item>
<item>Larger</item>
</string-array>
这是我的xml代码
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<Spinner
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/spinner"
android:layout_gravity="center_horizontal" />
答案 0 :(得分:1)
我建议您在onActivityCreated
回调中移动适配器的创建,当您确定通过调用getActivity()
时,您将获得活动的非null实例:
public class SettingFragment extends Fragment{
private View rootView;
Spinner spinner;
ArrayAdapter<CharSequence> adapter;
public SettingFragment(){
//required empty public constructor
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.fragment_setting, container, false);
spinner = (Spinner)rootView.findViewById(R.id.spinner);
return rootView;
}
@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
adapter = ArrayAdapter.createFromResource(getActivity(), R.array.select_font_size, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
}
}
答案 1 :(得分:0)
尝试使用Application上下文或实例化片段的活动的上下文。
adapter = ArrayAdapter.createFromResource(getApplicationContext(), R.array.select_font_size, android.R.layout.simple_spinner_item);
OR
adapter = ArrayAdapter.createFromResource(YOUR_ACTIVITY_CONTEXT_TO_BE_PASSED_INTO_FRAGMENT, R.array.select_font_size, android.R.layout.simple_spinner_item);