簡體   English   中英

帶有自定義建議適配器的 Android SearchView

[英]Android SearchView with custom suggestions adapter

我有一個帶有 SimpleCursorAdapter 的 SearchView,它從 SQLite 數據庫查詢建議。 查詢工作正常,SearchView 會彈出一個包含建議的列表。 但是,這些建議是不可見的。 例如,如果有兩個建議,可以看到有兩個列表條目,但沒有顯示文本。 SearchView 包含在 DialogFragment 中。

這是游標適配器和搜索視圖的初始化:

suggestionAdapter = new SimpleCursorAdapter(getActivity(),
            android.R.layout.simple_list_item_1,
            null,
            new String[]{"name"},
            new int[]{android.R.layout.simple_list_item_1},
            0);

final SearchView searchProd = (SearchView) dialogView.findViewById(R.id.searchProd);
searchProd.setOnQueryTextListener(this);
searchProd.setOnSuggestionListener(this);
searchProd.setSuggestionsAdapter(suggestionAdapter);

搜索建議在 onQueryTextChanged 中生成,其中生成新游標並將其注入建議適配器:

@Override
public boolean onQueryTextChange(String newText) {
    String[] columns = new String[]{"_id", "name"};
    String selection = "name LIKE ?";
    String[] selectionArgs = new String[]{newText + "%"};
    Cursor c = db.query(TABLE_NAME,
            columns,
            selection,
            selectionArgs,
            null,
            null,
            null);
    if (c.getCount() > 0) {
        suggestionAdapter.changeCursor(c);
        suggestionAdapter.notifyDataSetChanged();
        return true;
    } else {
        return false;
    }
}

問題是適配器將顯示列名稱為 SUGGEST_COLUMN_TEXT_1 的數據。 這是搜索下拉框中顯示的列。 但是你的光標在你的情況下使用數據庫列名 *name"。所以你必須做的是告訴適配器將你的數據庫列與你的適配器列相匹配。我這樣做的方法是創建一個類似於 hashMap 的 HashMap。 put(name, name + " as " SearcgManager.SUGGEST_COLUMN_TEXT_1) 然后在 SQLiteBuilder mSqliteBuilder 你可以在創建光標之前做 mSqliteBuilder.setProjectionMap(hashMap) 。我不使用 onQueryTextChange 搜索建議,但使用 contentprovider 和可搜索的配置文件. 但是因為列不匹配是為什么我相信你沒有在你的列表中看到你的建議

問題是您在SimpleCursorAdapter()的構造函數中為to字段提供了布局。 您應該改為為 textview 提供資源 ID,例如android.R.id.text1

我有一個類似的問題。 事實證明,我需要做的就是更改列出的條目中顯示的文本的顏色。 所以我有類似的東西

<TextView
        android:id="@+id/item"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textColor="#FFF2FF"
        />

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM