Android:Spinner OnSelectedItemListener

时间:2017-10-11 12:27:32

标签: android listview

我有一个带有ListView的应用程序,它显示用户所做的不同事务。我的代码似乎无法运作。

我现在遇到的问题是我想在此ListView上方添加一个Spinner,让用户选择是按日期,金额还是自己选择两个日期之间的间隔来排序交易。

继承我的代码只有微调器onSelectedItem:

public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_income, container, false);
        initializeComponents(view);
        registerListeners();
        spinnerOrderIncome = (Spinner) view.findViewById(R.id.spinnerOrderIncome);
        ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this.getActivity(), R.array.spinnerSortIncome, android.R.layout.simple_spinner_item);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinnerOrderIncome.setAdapter(adapter);
        spinnerOrderIncome.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                switch (spinnerOrderIncome.getSelectedItem().toString()) {
                    case "date":
                        lvIncome.setAdapter(new CustomIncomeListAdapter(activity, dbController.getDataFromIncomeTable()));
                        break;
                    case "amount":
                        lvIncome.setAdapter(new CustomIncomeListAdapter(activity, dbController.getSortedAmountFromIncomeTable()));
                        break;
                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
            }
        });

ListView已经使用此方法填充,该方法从DatabaseController获取列表:

public void populateListView() {
        lvIncome.setAdapter(new CustomIncomeListAdapter(activity, dbController.getDataFromIncomeTable()));
    }

在switch语句中可以看到这些方法,它们会改变ListView的顺序,但是当我选择不同的微调项目(日期,数量)时没有任何反应我是否在正确的轨道上?救命!

1 个答案:

答案 0 :(得分:0)

每次更改数据时,我都不会为listView分配新的适配器,而只是更新它包含的列表,然后调用notifyDataSetChanged通知适配器其数据已更改(因此视图将被重绘)。 / p>

类似的东西,我想(未经测试):

spinnerOrderIncome.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
    @Override
    public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
        CustomIncomeListAdapter myAdapter = (CustomIncomeListAdapter)lvIncome.getAdapter();
        myAdapter.getDataSet().clear();
        switch (spinnerOrderIncome.getSelectedItem().toString()) {
            case "date":
                myAdapter.getDataSet().addAll(dbController.getDataFromIncomeTable());
                break;
            case "amount":
                myAdapter.getDataSet().addAll(dbController.getSortedAmountFromIncomeTable());
                break;
        }
        myAdapter.notifyDataSetChanged();
    }
    @Override
    public void onNothingSelected(AdapterView<?> parent) {
    }
}