在AlertDialog中使用自定义适配器的AutoCompleteTextView

时间:2015-09-04 14:35:19

标签: android adapter alertdialog autocompletetextview

我在AlertDialog中需要一个AutoCompleteTextView,我已将其置于onOptionsItemSelected()中。我已经制作了一个自定义适配器来覆盖getFilter()方法。我无法弄清楚为什么,但AutoCompleteTextView没有显示下拉菜单。

onOptionsItemSelected()的代码:

@Override
public boolean onOptionsItemSelected(MenuItem item) {

    if (actionBarDrawerToggle.onOptionsItemSelected(item)) {
        return true;
    }

    switch (item.getItemId()) {
    case R.id.action_add: {

        AlertDialog.Builder alert = new AlertDialog.Builder(this);

        LinearLayout ll = new LinearLayout(BaseActivity.this);
        ll.setOrientation(LinearLayout.VERTICAL);

        final AutoCompleteTextView code = new   AutoCompleteTextView(BaseActivity.this);

        alert.setMessage("Add");

        code.setHint("Stock Code");
        acAdapter = new AutoCompleteAdapter(BaseActivity.this, android.R.layout.simple_dropdown_item_1line); 
        code.setAdapter(acAdapter);
        code.setThreshold(1);
        ll.addView(code);

        alert.setView(ll);

        alert.setPositiveButton("Add",
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog,
                            int whichButton) {
                                          ...
                }
         }
         break;
    }
    }
}   

AutoCompleteAdapter类的代码:

public class AutoCompleteAdapter extends ArrayAdapter<String> implements Filterable {
    private ArrayList<String> mData;
    private String mData2;

    public AutoCompleteAdapter(Context context, int textViewResourceId) {
        super(context, textViewResourceId);
        mData = new ArrayList<String>();
    }

    @Override
    public int getCount() {
        return mData.size();
    }

    @Override
    public String getItem(int index) {
        return mData.get(index);
    }

    @Override
    public Filter getFilter() {
        Filter myFilter = new Filter() {
            @Override
            protected FilterResults performFiltering(CharSequence constraint) {
                FilterResults filterResults = new FilterResults();
                if(constraint != null) {
                    mData.add("google");
                    filterResults.values = mData;
                    filterResults.count = mData.size();
                }  
                return filterResults;
            }

            @Override
            protected void publishResults(CharSequence contraint, FilterResults results) {
                if(results != null && results.count > 0) {
                    notifyDataSetChanged();
                }
                else {
                    notifyDataSetInvalidated();
                }
            }
        };
        return myFilter;
    }
}

我的实施出了什么问题?

PS: 这里的performFiltering()方法为了简单起见仅将“google”添加到ArrayList。我真的需要创建自定义适配器。

谢谢。

0 个答案:

没有答案