开发者

Can anyone please help me correct this code?

开发者 https://www.devze.com 2023-01-22 16:03 出处:网络
I get an error at adapter.getFilter().filter(s) in the onTextChanged() function. I was following this - How to dynamically update a ListView on Android - to creater a filterable List inside a Dialog.

I get an error at adapter.getFilter().filter(s) in the onTextChanged() function. I was following this - How to dynamically update a ListView on Android - to creater a filterable List inside a Dialog.

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);
    }
};
}
开发者_JAVA百科


You are not initializing the adapter member of your class.

Try changing:

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

to:

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

There is a portion of that article that says

Turns out that is pretty easy. To run a quick test, add this line to your onCreate() call

adapter.getFilter().filter(s);

Notice that you will need to save your ListAdapter to a variable to make this work - I have saved my ArrayAdapter<String> from earlier into a variable called 'adapter'.

Although that is misleading because the code posted doesn't reflect that change.

0

精彩评论

暂无评论...
验证码 换一张
取 消