Android onItemSelected Spinner未激活

时间:2014-05-01 03:17:56

标签: java android android-fragments android-spinner onitemselectedlistener

当我更改我的微调器视图时,我的应用程序没有启动onItemSelected方法。 它应该工作正常,但它不起作用。

class UnitConverter extends Fragment implements OnItemSelectedListener{
    Spinner spinner, spinner2;
    ArrayAdapter<CharSequence> adapter, kilogramAdapter, metreAdapter;
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        super.onCreateView(inflater,container,savedInstanceState);
        View v = inflater.inflate(R.layout.activity_converter, container, false);
        spinner = (Spinner) v.findViewById(R.id.SI_spinner);
        spinner2 = (Spinner) v.findViewById(R.id.spinner1);

        adapter = ArrayAdapter.createFromResource(getActivity(), R.array.si_array, android.R.layout.simple_spinner_item);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        metreAdapter = ArrayAdapter.createFromResource(getActivity(), R.array.metre_array, android.R.layout.simple_spinner_item);
        metreAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        kilogramAdapter = ArrayAdapter.createFromResource(getActivity(), R.array.kilogram_array, android.R.layout.simple_spinner_item);
        kilogramAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

        spinner.setAdapter(adapter);
        spinner2.setAdapter(metreAdapter);
        return v;
    }

    @Override
    public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3){
        spinner2.setAdapter(kilogramAdapter);
    }
    @Override
    public void onNothingSelected(AdapterView<?> arg0) {

    }
}

3 个答案:

答案 0 :(得分:1)

您需要设置Spinner项目选择Listener

spinner.setOnItemSelectedListener(this);

答案 1 :(得分:1)

当您要使用ListviewSpinner时,您希望触发代码下方的选择

spinner.setOnItemSelectedListener(this);

答案 2 :(得分:1)

您需要使用您的微调器注册侦听器,如下面的代码

如果您正在实施OnItemSelectedListener,就像您在提供的代码中所做的那样。然后像这样注册听众

spinner.setOnItemSelectedListener(this);

或者如果您要创建一个实现OnItemSelectedListener接口的新类。

然后您可以使用您的微调器视图注册该类

 spinner.setOnItemSelectedListener(new MyCustomListener());


private class MyCustomListener implements OnItemSelectedListener
{
 @Override
    public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3){
        // Write your logic what you want to do on selecting the item
    }
    @Override
    public void onNothingSelected(AdapterView<?> arg0) {

    }
}