0

我正在尝试实现对通过 SimpleCursorAdapter 创建的 ListView 的搜索。我尝试了各种方法,以下是我到目前为止所拥有的,但它不起作用。我希望能够输入 EditText 并且我的列表会根据搜索进行调整。任何帮助将不胜感激,以下是我的代码:

    private FoodDatabase foodDB;
private CalendarDBAdapter calendarDB;
private ListView fruitsListVIew;
private String datePassed;
private View dialogView;
private EditText search;
private SimpleCursorAdapter myCursorAdapter;


@Override
protected void onCreate(Bundle savedInstanceState) 
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.fruits);        
    fruitsListVIew = (ListView)this.findViewById(R.id.fruitsListView);
    search = (EditText)this.findViewById(R.id.search_box);
    datePassed = GlobalVars.getDate();

    openDB();
    populateLV();

    search.addTextChangedListener(new TextWatcher() 
    {           
        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) 
        {
            myCursorAdapter.getFilter().filter(s.toString());
        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) 
        {

        }

        @Override
        public void afterTextChanged(Editable s) 
        {

        }
    });
}

    private void populateLV()
{
    String fruitID = "10";
    final Cursor c = foodDB.getFoodByGroup(fruitID);

    //allow activity to close cursor
    startManagingCursor(c);

    //Mapping from cursor to view fields
    String[] fieldNames = new String[] {FoodDatabase.FOOD_ITEM_NAME, FoodDatabase.CALORIES, FoodDatabase.FAT,
                                        FoodDatabase.MEASURE, FoodDatabase.TYPE_OF_MEASRE};
    int[] viewIds = new int[] {R.id.foodNameTxt, R.id.calorieDB, R.id.fatDB, R.id.servingDB, R.id.measureTxt};

    //create adapter to map columns to view exercise UI
    myCursorAdapter = new SimpleCursorAdapter(this, R.layout.foods_data_layout, c, fieldNames, viewIds);

    //Set the adapter for the list view
    fruitsListVIew.setAdapter(myCursorAdapter);
    fruitsListVIew.setTextFilterEnabled(true);
    fruitsListVIew.setOnItemClickListener(new OnItemClickListener() 
    {

        @Override
        public void onItemClick(AdapterView<?> parent, View v, int position, long id) 
        {
            qtyDialog(v);
        }

    });
}

我可以输入文本,但没有任何反应。干杯

4

1 回答 1

0

尝试这个

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) 
    {
        myCursorAdapter.getFilter().filter(s.toString());
        myCursorAdapter.notifyDataSetChanged();
    }

在我看来,您需要一个 FilterQueryProvider :)

myCursorAdapter.setFilterQueryProvider(new FilterQueryProvider() {

    @Override
    public Cursor runQuery(CharSequence constraint) {
        String partialValue = constraint.toString();
        return itemData.getAllSuggestedValues(partialValue);

    }
});

检查这个 -使用 EditText 过滤 SimpleCursorAdapter 支持的 ListView

于 2013-09-18T20:11:27.690 回答