Android AutoCompleteTextView作为ListView标头

时间:2013-02-07 06:09:14

标签: android listview autocompletetextview

我正在尝试将AutoCompleteTextView设置为ListView标头,但如果我这样做,则自动完成框永远不会出现。用于创建自动完成视图的代码直接来自google文档中的Hello, AutoComplete教程。 COUNTRIES阵列也来自那里。

protected void onCreate(Bundle savedInstanceState) {
requestWindowFeature(Window.FEATURE_NO_TITLE);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

ListView myList = (ListView) findViewById(R.id.ResultList);

LayoutInflater layoutInflater = (LayoutInflater) this.getSystemService(LAYOUT_INFLATER_SERVICE);
TableLayout searchHeader = (TableLayout) layoutInflater.inflate(R.layout.search_header, null); 
myList.addHeaderView(searchHeader, null, false);

final AutoCompleteTextView textView = (AutoCompleteTextView) myList.findViewById(R.id.edit);
ArrayAdapter<String> searchAdapter = new ArrayAdapter<String>(this,
        android.R.layout.simple_dropdown_item_1line, COUNTRIES);
textView.setAdapter(searchAdapter);
textView.setThreshold(1);

        //Dummy data for listview.

String[] listContent = {
        "test", "test", "test", "test",
        "test", "test", "test", "test"
};
ArrayAdapter<String> adapter = new SearchResultAdapter(this, listContent);
myList.setAdapter(adapter);

}

作为测试,我添加了一个TextChangedListener来尝试强制显示对话框

    textView.addTextChangedListener(new TextWatcher() {

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
        }

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

        @Override
        public void afterTextChanged(Editable s) {
            textView.showDropDown();
        }
    });

出现对话框但几乎立即关闭。我想知道从列表视图中冒出的某种事件是否导致了这种情况?

2 个答案:

答案 0 :(得分:6)

This question关于ListView&amp;中的EditText视图的焦点。一些AutoCompleteTextView源代码的阅读帮助我找到答案。将ListView上的焦点顺序设置为afterDescendants可以使对话框正常显示。

<ListView
    android:id="@+id/ResultList"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:layout_marginBottom="50dip"
    android:descendantFocusability="afterDescendants"
    android:fadingEdge="none" >
</ListView>

答案 1 :(得分:0)

在您的XML文件中使用autocompletetextview可能会有所帮助