[英]Spinner Showing in XML but Not When Loading App
我的片段中包含以下内容,并且尝试创建一个显示数字1-5作为选择选项的微调器:
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View rootview = inflater.inflate(R.layout.fragment_create, container, false);
mAddImageButton = (Button) rootview.findViewById(R.id.add_image_button);
mSelectNumberofPollAnswers = (Spinner) rootview.findViewById(R.id.number_of_answers_spinner);
// Inflate the layout for this fragment
// Create an ArrayAdapter using the string array and a default spinner layout
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(getActivity().getApplicationContext(),
R.array.number_of_poll_answers, android.R.layout.simple_spinner_item);
// Specify the layout to use when the list of choices appears
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// Apply the adapter to the spinner
mSelectNumberofPollAnswers.setAdapter(adapter);
return inflater.inflate(R.layout.fragment_create, container, false);
}
Strings.xml:
<string-array name="number_of_poll_answers">
<item>1</item>
<item>2</item>
<item>3</item>
<item>4</item>
<item>5</item>
</string-array>
XML:
<Spinner
android:id="@+id/number_of_answers_spinner"
android:layout_width="fill_parent"
android:layout_height="0dp"
android:layout_weight=".3"/>
在onCreateView()
方法中,您将在return
语句中返回一个未初始化的新View
。 相反,您想返回在此之前膨胀并初始化的View
。 也就是说,将return
语句更改为:
return rootview;
尝试:
return rootview;
代替
return inflater.inflate(R.layout.fragment_create, container, false);
您必须像这样返回rootView
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View rootview = inflater.inflate(R.layout.fragment_create, container, false);
mAddImageButton = (Button) rootview.findViewById(R.id.add_image_button);
mSelectNumberofPollAnswers = (Spinner) rootview.findViewById(R.id.number_of_answers_spinner);
// Inflate the layout for this fragment
// Create an ArrayAdapter using the string array and a default spinner layout
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(getActivity().getApplicationContext(),
R.array.number_of_poll_answers, android.R.layout.simple_spinner_item);
// Specify the layout to use when the list of choices appears
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// Apply the adapter to the spinner
mSelectNumberofPollAnswers.setAdapter(adapter);
return rootview;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.