onListItemClick()无法处理ArrayAdapter(Android)中的筛选搜索列表

时间:2015-01-29 17:21:41

标签: android search android-listview android-arrayadapter textwatcher

我有一个列表视图,我已经实现了onListItemClick()。它工作得很好但是当我使用搜索过滤列表时,它会打开错误的列表项(有时甚至在过滤列表中看不到)。下面是我的代码,不知道我错过了什么或做错了什么。请参阅内联注释以获取代码的功能。任何帮助将不胜感激。

private static final int EDITOR_ACTIVITY_REQUEST = 2001;
private DataSource mSource;
private ArrayAdapter<SampleData> mAdapter;
private EditText mSearchField;
private List<SampleData> mDataList;
private SampleData mData;
private Intent mIntent;

// done in onCreate()
mSource = new DataSource(this);
updateDisplay();

// set up in onCreateOptionsMenu()
mSearchField = (EditText) menu.findItem(R.id.action_search).getActionView();
mSearchField.addTextChangedListener(searchTextWatcher);

// method to refresh display
private void updateDisplay() {
        // fetch data from the database and display in list view
        mDataList = mSource.retrieveAllData();
        mAdapter = new ArrayAdapter<>(this, R.layout.list_item_layout, mDataList);
        setListAdapter(mAdapter);

    }


    // respond to list item clicks
    @Override
    protected void onListItemClick(ListView l, View v, int position, long id) {
        // view data of an item pressed on
        editData(position);
    }

    // edit the data
    protected void editData(int position) {
        mData = mDataList.get(position);
        mIntent = new Intent(this, DataEditor.class);
        mIntent.putExtra(Constants.KEY, mData.getKey());
        mIntent.putExtra(Constants.TEXT, mData.getText());
        startActivityForResult(mIntent, EDITOR_ACTIVITY_REQUEST);
    }

// Search TextWatcher
    private TextWatcher searchTextWatcher = new TextWatcher() {

        @Override
        public void afterTextChanged(Editable s) {
            String searchText = mSearchField.getText().toString()
                    .toLowerCase(Locale.getDefault());
            mAdapter.getFilter().filter(searchText);

            // tried these but never worked
            /**
             * mAdapter.notifyDataSetInvalidated(); 
             * mAdapter.notifyDataSetChanged();
             * getListView().setAdapter(mAdapter);
             */
        }

        @Override
        public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
                int arg3) {

        }

        @Override
        public void onTextChanged(CharSequence arg0, int arg1, int arg2,
                int arg3) {

        }

    };

1 个答案:

答案 0 :(得分:0)

而不是mDataList.get(position),请使用mAdapter.getItem(position)position基于当前列表内容,mDataList是原始未过滤列表内容。