自动填充功能无效

时间:2012-08-23 17:03:22

标签: android autocompletetextview

我有一个包含名称和AutoCompleteTextView的列表。我需要AutoCompleteTextView按用户输入的字符串过滤名称,但我不知道我做错了什么因为AutoCompleteTextView不起作用。你能救我吗?

这是我的代码:

cursor = socioData.getAllSocios();
adapter = new SimpleCursorAdapter(
        this,
        android.R.layout.simple_dropdown_item_1line,
        cursor,
        new String[]{Socio.C_NOME},
        new int[]{android.R.id.text1}
        );

filterText = (AutoCompleteTextView)findViewById(R.id.search);
filterText.setThreshold(1);
filterText.setAdapter(adapter);
adapter.setCursorToStringConverter(new CursorToStringConverter() {
    @Override
    public String convertToString(Cursor cursor) {
        //return cursor.getString(1);
        final int colIndex = cursor.getColumnIndexOrThrow(Socio.C_NOME);
        return cursor.getString(colIndex);
    }
});

adapter.setFilterQueryProvider(new FilterQueryProvider() {
    @Override
    public Cursor runQuery(CharSequence constraint){
        return getContentResolver().query(Data.CONTENT_URI,
                Socio.ALL_COLUMNS,
                Socio.C_NOME + " like '%"+constraint+"%'",
                null,
                Socio.C_NOME +" ASC");
    }
});  

filterListener = new TextWatcher() {
    @Override
    public void onTextChanged(CharSequence s, int arg1, int arg2, int arg3) {
        if ("".equals(s))
            adapter.getFilter().filter(null);
        else
            adapter.getFilter().filter(s.toString());   
    }

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

    @Override
    public void afterTextChanged(Editable arg0) {}
};

1 个答案:

答案 0 :(得分:0)

你似乎试图做太多......这里有几个简化:

  • 我看不到你在哪里使用TextWatcher,但事实并非如此 需要。实际上它可能会阻止AutoCompleteTextView 工作。所以你应该删除它。

  • 在您的FilterQueryProvider和getAllSocios()中,您应该只询问 对于列_idSocio.C_NOME,因为这些是唯一的 您使用的两列。

  • 只需使用setStringConversionColumn()代替a CursorToStringConverter:

所有这些你只需要:

cursor = socioData.getAllSocios();
adapter = new SimpleCursorAdapter(
        this,
        android.R.layout.simple_dropdown_item_1line,
        cursor,
        new String[]{Socio.C_NOME},
        new int[]{android.R.id.text1} );

adapter.setFilterQueryProvider(new FilterQueryProvider() {
    @Override
    public Cursor runQuery(CharSequence constraint){
        // Stop the FQP from looking for nothing
        if(constraint == null)
            return null;

        return getContentResolver().query(Data.CONTENT_URI,
            new String[] {"_id", Socio.C_NOME},
            Socio.C_NOME + " like ?", 
            "'%"+constraint+"%'",
            Socio.C_NOME);
    }
});
adapter.setStringConversionColumn(cursor.getColumnIndex(Socio.C_NOME));

filterText = (AutoCompleteTextView)findViewById(R.id.search);
filterText.setThreshold(1);
filterText.setAdapter(adapter);

希望有所帮助!