2011-06-28 49 views
0

我完全難住!我一直在尋找年齡,但找不到解決方案。我有一種感覺,它會很容易!如何在用戶輸入文字時使用光標更新列表視圖

Anway,我有一個綁定到遊標的listview,並且每次用戶輸入一個字母時,我都希望listview能夠搜索數據庫並返回結果。這聽起來很容易,但我無法弄清楚。先謝謝您的幫助。

這裏是我的代碼至今:

public class MyList extends ListActivity { 


    public static final String KEY_ROWID = "headwords._id"; 
    public static final String KEY_WORDS = "headwords.words"; 
    private ListAdapter adapter; 
    private DbManager myDb; 


    /** Called when the activity is first created. */ 
    @Override 
    public void onCreate(Bundle icicle) { 
     super.onCreate(icicle); 
     setContentView(R.layout.item_list); 


     myDb = new DbManager(this); 
     myDb.open(); 
     Cursor mCursor = myDb.startsWith("a"); 
     startManagingCursor(mCursor); 



     try { 
     adapter = new SimpleCursorAdapter(this, android.R.layout.simple_list_item_1, mCursor, 
       new String[] { KEY_WORDS, KEY_ROWID }, 
       new int[] { android.R.id.text1, android.R.id.text2 }); 
       setListAdapter(adapter); 

     } catch (Exception e) { 
      Log.i("adapter error Here!", ">>>>>>>>>>> Error!" + e.toString()); 
     } 








     EditText myET = (EditText) findViewById(R.id.search_text); 
     myET.addTextChangedListener(new TextWatcher() { 
      @Override 
      public void onTextChanged(CharSequence s, int start, int before, int count) { 
       //code which would change listview to only show item that match what is being typed in 
      } 

      @Override 
      public void afterTextChanged(Editable s) { 
      } 

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

     }); 

    } 
+0

使你的mCursor最終和調用mCursor.requery()onTextChanged; – Gopal

+0

重新查詢將不起作用,因爲它不會像以前一樣查詢。 –

回答

0

先mCursor成員:

private Cursor mCursor; 

@Override 
public void onCreate(Bundle icicle) { 
    mCursor = myDb.startsWith("a"); 
} 

然後在我的例子,我走的是CharSequence的第一個字母,但是這可能不是做你想做的事情,但關鍵是changeCursor();

@Override 
public void onTextChanged(CharSequence s, int start, int before, int count) { 
    mCursor = myDb.startsWith(s.toString.substring(0,1)); 
    adapter.changeCursor(mCursor); 
} 
+0

感謝您抽出寶貴的時間和快速!這段代碼看起來不錯,但是eclipse說的是ChangeCursor的方法對ListAdapter類型是未定義的。任何想法爲什麼? –

+0

您的適配器成員應該轉換爲SimpleCursorAdapter。所以改變私人ListAdapter適配器;私人SimpleCursorAdapter適配器; –

+0

呵呵!我認爲我該上牀睡覺了。感謝您的幫助,我現在可以完美地工作,即使它有點慢。順便說一下,帽子rulz先生! –

相關問題