簡體   English   中英

誰能幫我糾正此代碼?

[英]Can anyone please help me correct this code?

我在onTextChanged()函數中的adapter.getFilter()。filter(s)處收到錯誤。 我一直在關注- 如何在Android上動態更新ListView-在對話框中創建可過濾列表。

public class CustomizeDialog extends Dialog implements OnClickListener {

private final String[] cityList = {"Seattle", "London"}; private EditText filterText = null;
ArrayAdapter<String> adapter = null;

public CustomizeDialog(Context context) {
    super(context);

    /** Design the dialog in main.xml file */

    setContentView(R.layout.main);
    filterText = (EditText) findViewById(R.id.EditBox);
    filterText.addTextChangedListener(filterTextWatcher);

    this.setTitle("Select");
    list = (ListView) findViewById(R.id.List);
    list.setAdapter(new ArrayAdapter<String>(context, android.R.layout.simple_list_item_1, cityList));
}

@Override
public void onClick(View v) {
    /** When OK Button is clicked, dismiss the dialog */
}
private TextWatcher filterTextWatcher = new TextWatcher() {

    public void afterTextChanged(Editable s) {
    }

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

    public void onTextChanged(CharSequence s, int start, int before,
            int count) {
        adapter.getFilter().filter(s);
    }
};
}

您沒有初始化類的adapter成員。

嘗試更改:

list.setAdapter(new ArrayAdapter<String>(context, android.R.layout.simple_list_item_1, cityList));

至:

adapter = new ArrayAdapter<String>(context, android.R.layout.simple_list_item_1, cityList);
list.setAdapter(adapter);

那篇文章的一部分說

事實證明,這很容易。 要運行快速測試,請將此行添加到onCreate()調用中

adapter.getFilter().filter(s);

請注意,您需要將ListAdapter保存到一個變量中才能完成此工作-我已將ArrayAdapter<String>從較早版本保存到一個名為'adapter'的變量中。

盡管這會產生誤導,因為發布的代碼沒有反映出這種變化。

暫無
暫無

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

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