Spinner以XML格式显示但不在加载应用程序时显示

时间:2016-07-04 23:40:46

标签: java android xml android-layout

我的片段中有以下内容,我正在尝试创建一个显示数字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"/>

3 个答案:

答案 0 :(得分:3)

onCreateView()方法中,您在View语句中返回了一个未初始化的新return。相反,您希望在此之前返回您膨胀并初始化的View。也就是说,将return语句更改为:

return rootview;

答案 1 :(得分:1)

尝试:

return rootview;

而不是

return inflater.inflate(R.layout.fragment_create, container, false);

答案 2 :(得分:1)

您必须像这样返回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;
}