不能从Text Spinner中获取getSelectedItem()

时间:2015-11-21 05:18:44

标签: java android string spinner android-spinner

我用以下String []数组调用我的Spinner:

    String[] quantity = {"1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20"};
    SetupQuantitySpinner(quantity);

这是我的微调器,它包含上面的String []数组:

public void SetupQuantitySpinner(String[] quantity) {
    Spinner spnr;
    spnr = (Spinner)view.findViewById(R.id.spinner_quantity);
    String productQuantity = spnr.getSelectedItem().toString();
    System.out.println(productQuantity);
    ArrayAdapter<String> adapter = new ArrayAdapter<String>(
            getActivity(),
            R.layout.custom_spinner,
            R.id.text_main_seen,
            quantity);
    spnr.setAdapter(adapter);
}

为什么我无法从Spinner中获取所选值?这导致我的虚拟机崩溃,没有其他解释。 Spinner工作,因为如果我删除行getSelectedItem(),一切正常。

1 个答案:

答案 0 :(得分:2)

因为当你致电getSelectedItem时,你已经为旋转器设置了适配器。所以你应该在setAdapter之后调用它。就像这样:

public void SetupQuantitySpinner(String[] quantity) {
Spinner spnr;
spnr = (Spinner)view.findViewById(R.id.spinner_quantity);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(
        getActivity(),
        R.layout.custom_spinner,
        R.id.text_main_seen,
        quantity);
spnr.setAdapter(adapter);
spnr.setSelection(0);
String productQuantity = quantity[spnr.getSelectedItemPosition()];
System.out.println(productQuantity);
}