Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
您现在的位置: Android教程網 >> Android系統教程 >  >> Android 技術 >> Android 開發實例

Android 二級下拉菜單與實時搜索聯動的實現方法

編輯:Android 開發實例

需求很常見:頁面上方一個搜索框,下方一個兩級菜單;有輸入時展示搜索結果列表,清空輸入後恢復菜單。本文用 ExpandableListView + ListView 的顯示切換來實現。

一、目標效果

默認狀態顯示二級菜單,一級項可展開收攏。

一旦在搜索框輸入內容,菜單隱藏,列表展示匹配結果。

二、界面結構

(1)主框架,自上而下是輸入框、搜索結果列表、二級菜單(部分屬性已省略,完整版見源碼):

 <?xml version="1.0" encoding="utf-8"?>
<LinearLayout>
    <LinearLayout android:id="@+id/city_middle">
        <EditText
            android:id="@+id/txtfind"
            android:hint="請輸入" >
        </EditText>
        <ListView
            android:id="@+id/listfind" >
        </ListView>
        <ExpandableListView
            android:id="@+id/exList" />
    </LinearLayout>
</LinearLayout>

注意: ListView 與 ExpandableListView 是層疊關係下互相切換顯示,同一時刻只有一個可見。

(2)一級菜單樣式,右側圖標用來區分是否展開:

 <?xml version="1.0" encoding="utf-8"?>
<LinearLayout>
    <TextView
        android:id="@+id/group" >
    </TextView>
    <ImageView
        android:id="@+id/tubiao">
    </ImageView>
</LinearLayout>

(3)二級菜單樣式:

 <?xml version="1.0" encoding="utf-8"?>
<LinearLayout>
    <TextView
        android:id="@+id/child">
    </TextView>
</LinearLayout>

三、代碼實現

(1)定義菜單數據結構,一級用 List,二級用「List 的 List」:

 public static List<BasicNameValuePair> fatherList = new ArrayList<BasicNameValuePair>();
public static List<List<BasicNameValuePair>> childList = new ArrayList<List<BasicNameValuePair>>();

生成測試數據:

 for (int i = 0; i < 20; i++) {
    fatherList.add(new BasicNameValuePair("father" + i, "father" + i));
    List<BasicNameValuePair> cList = new ArrayList<BasicNameValuePair>();
    for (int j = 0; j < 5; j++) {
        cList.add(new BasicNameValuePair("child" + i + ":" + j, "child" + i + ":" + j));
    }
    childList.add(cList);
}

(2)搜索結果適配器。構造時就完成匹配過濾,把命中的項收集到內部 list:

 protected class ListAdapter extends BaseAdapter {

    private LayoutInflater mInflater;
    private List<BasicNameValuePair> list = new ArrayList<BasicNameValuePair>();

    public ListAdapter(Context context, String strin) {
        mInflater = LayoutInflater.from(context);
        // 遍歷二級數據做匹配
        for (int i = 0; i < childList.size(); i++) {
            for (int j = 0; j < childList.get(i).size(); j++) {
                String tmp = childList.get(i).get(j).getValue();
                if (tmp.indexOf(strin) >= 0) {
                    list.add(new BasicNameValuePair(
                            childList.get(i).get(j).getName(), tmp));
                }
            }
        }
    }

    public int getCount() {
        return list.size();
    }

    public Object getItem(int position) {
        return position;
    }

    public long getItemId(int position) {
        return position;
    }

    public View getView(final int position, View convertView, ViewGroup parent) {
        convertView = mInflater.inflate(R.layout.child, null);
        TextView title = (TextView) convertView.findViewById(R.id.child);
        title.setText(list.get(position).getValue());
        return convertView;
    }
}

初始化時默認隱藏:

 list = (ListView) findViewById(R.id.listfind);
list.setVisibility(View.GONE);

(3)二級菜單適配器。這裡的關鍵是 getGroupView 中根據 isExpanded 參數切換箭頭圖標:

 protected class ExAdapter extends BaseExpandableListAdapter {

    @Override
    public int getGroupCount() {
        return fatherList.size();
    }

    @Override
    public int getChildrenCount(int groupPosition) {
        return childList.get(groupPosition).size();
    }

    @Override
    public Object getGroup(int groupPosition) {
        return fatherList.get(groupPosition).getValue();
    }

    @Override
    public Object getChild(int groupPosition, int childPosition) {
        return childList.get(groupPosition).get(childPosition).getValue();
    }

    @Override
    public long getGroupId(int groupPosition) {
        return groupPosition;
    }

    @Override
    public long getChildId(int groupPosition, int childPosition) {
        return childPosition;
    }

    @Override
    public View getGroupView(int groupPosition, boolean isExpanded,
                             View convertView, ViewGroup parent) {
        View view = convertView;
        if (view == null) {
            LayoutInflater inflater = (LayoutInflater)
                    getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            view = inflater.inflate(R.layout.group, null);
        }
        TextView t = (TextView) view.findViewById(R.id.group);
        t.setText(fatherList.get(groupPosition).getValue());

        // 依展開狀態切換箭頭
        ImageView gImg = (ImageView) view.findViewById(R.id.tubiao);
        if (isExpanded) {
            gImg.setBackgroundResource(R.drawable.mm_submenu_down_normal);
        } else {
            gImg.setBackgroundResource(R.drawable.mm_submenu_normal);
        }
        return view;
    }

    @Override
    public View getChildView(int groupPosition, int childPosition, boolean isLastChild,
                             View convertView, ViewGroup parent) {
        View view = convertView;
        if (view == null) {
            LayoutInflater inflater = (LayoutInflater)
                    getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            view = inflater.inflate(R.layout.child, null);
        }
        TextView t = (TextView) view.findViewById(R.id.child);
        t.setText(childList.get(groupPosition).get(childPosition).getValue());
        return view;
    }

    @Override
    public boolean hasStableIds() {
        return true;
    }

    @Override
    public boolean isChildSelectable(int groupPosition, int childPosition) {
        return true;
    }
}

初始化菜單,順手去掉系統默認的分組指示箭頭和分隔線,因為我們自己畫了圖標:

 exList = (ExpandableListView) findViewById(R.id.exList);
exList.setAdapter(new ExAdapter());
exList.setGroupIndicator(null);     // 隱藏默認指示器
exList.setDivider(null);            // 去掉分隔線

(4)搜索事件。用 TextWatcher 監聽輸入變化,即時切換兩個控件的顯示:

 txtFind = (EditText) findViewById(R.id.txtfind);
txtFind.addTextChangedListener(new TextWatcher() {
    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) { }

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

    @Override
    public void afterTextChanged(Editable s) {
        if (s != null && !s.toString().equals("")) {
            // 有輸入 → 顯示搜索結果
            list.setAdapter(new ListAdapter(DWinterDemoActivity.this, s.toString()));
            list.setVisibility(View.VISIBLE);
            exList.setVisibility(View.GONE);
        } else {
            // 無輸入 → 恢復菜單
            list.setVisibility(View.GONE);
            exList.setVisibility(View.VISIBLE);
        }
    }
});

(5)進入頁面時不要自動彈出軟鍵盤:

 getWindow().setSoftInputMode(
         WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);

四、實用化改進建議

示例把匹配邏輯放在 ListAdapter 的構造函數裡,每次輸入變化都 new 一個新對象並全量遍歷。數據量小沒問題,但當二級數據上千條時,這種做法會造成明顯的輸入卡頓。更好的方案是:

1. 加防抖。用 Handler 延遲 200~300ms 再執行搜索,避免用戶快速輸入時觸發幾十次無效計算。

2. 異步匹配。把過濾放到子線程,完成後在主線程刷新 Adapter。

3. 複用 Adapter。只調 notifyDataSetChanged 更新數據,而不是反復 new。

4. 補上 convertView 複用。示例的 getView 每次都 inflate,滑動時內存抖動明顯,應按 ViewHolder 模式複用。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved