2010-11-01 131 views
1

我在onTextChanged()函数中的adapter.getFilter()。filter(s)处得到一个错误。我正在关注这个 - How to dynamically update a ListView on Android - 在对话框中创建一个可过滤列表。任何人都可以请帮我改正这段代码吗?

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); 
    } 
}; 
} 

回答

1

您未初始化您的班级的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'

虽然这是误导,因为发布的代码并不反映这种变化。

+0

非常感谢。对不起,问这样一个愚蠢的问题,我是新来的android。再次感谢 – 2010-11-01 05:35:16

+0

这个社区全是关于学习,不需要道歉,乐于帮助。 – 2010-11-01 05:36:55

+0

如何摧毁物体?我的意思是我在哪里调用filterText.removeTextChangedListener(filterTextWatcher); ? – 2010-11-01 06:22:35

相关问题