本文實例講述了Android編程實現仿美團或淘寶的多級分類菜單效果。分享給大家供大家參考,具體如下:
這里要實現的是諸如美團/淘寶/百度糯米 多級分類菜單效果。當分類數量非常多時可以考慮采用兩級分類,而諸如美團這種表現方式是一個不錯的選擇。
首先上效果圖:

主要代碼:
1. PopupWindow初始化過程:
popupWindow = new PopupWindow(this);View view = LayoutInflater.from(this).inflate(R.layout.popup_layout, null);leftLV = (ListView) view.findViewById(R.id.pop_listview_left);rightLV = (ListView) view.findViewById(R.id.pop_listview_right);popupWindow.setContentView(view);popupWindow.setBackgroundDrawable(new PaintDrawable());popupWindow.setFocusable(true);popupWindow.setHeight(ScreenUtils.getScreenH(this) * 2 / 3);popupWindow.setWidth(ScreenUtils.getScreenW(this));popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() { @Override public void onDismiss() { darkView.startAnimation(animOut); darkView.setVisibility(View.GONE); leftLV.setSelection(0); rightLV.setSelection(0); }});2.左側菜單點擊事件:
//左側ListView點擊事件leftLV.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { //二級數據 List<SecondClassItem> list2 = firstList.get(position).getSecondList(); //如果沒有二級類,則直接跳轉 if (list2 == null || list2.size() == 0) { popupWindow.dismiss(); int firstId = firstList.get(position).getId(); String selectedName = firstList.get(position).getName(); handleResult(firstId, -1, selectedName); return; } FirstClassAdapter adapter = (FirstClassAdapter) (parent.getAdapter()); //如果上次點擊的就是這一個item,則不進行任何操作 if (adapter.getSelectedPosition() == position){ return; } //根據左側一級分類選中情況,更新背景色 adapter.setSelectedPosition(position); adapter.notifyDataSetChanged(); //顯示右側二級分類 updateSecondListView(list2, secondAdapter); }});3. 右側菜單點擊事件:
//右側ListView點擊事件rightLV.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { //關閉popupWindow,顯示用戶選擇的分類 popupWindow.dismiss(); int firstPosition = firstAdapter.getSelectedPosition(); int firstId = firstList.get(firstPosition).getId(); int secondId = firstList.get(firstPosition).getSecondList().get(position).getId(); String selectedName = firstList.get(firstPosition).getSecondList().get(position) .getName(); handleResult(firstId, secondId, selectedName); }});4.頂部標簽點擊事件(即顯示/隱藏 分類菜單)
if (popupWindow.isShowing()) { popupWindow.dismiss();} else { popupWindow.showAsDropDown(findViewById(R.id.main_div_line)); popupWindow.setAnimationStyle(-1); //背景變暗 darkView.startAnimation(animIn); darkView.setVisibility(View.VISIBLE);}5.根據左側點擊,刷新右側ListView
//刷新右側ListViewprivate void updateSecondListView(List<SecondClassItem> list2, SecondClassAdapter secondAdapter) { secondList.clear(); secondList.addAll(list2); secondAdapter.notifyDataSetChanged();}完整實例代碼點擊此處本站下載。
希望本文所述對大家Android程序設計有所幫助。
新聞熱點
疑難解答