最近要实现一个点下拉分类筛选菜单, 选全国区域联动, 这里数据时参照网上本地存放省市区数据库.
由于项目实际要满足从接口异步获取, 所以整体采用MVP做了小拆分. 自定义的级联菜单CascadingMenuView作为VIew, 外部传入处理逻辑的presenter, 为了简化, 这里的请求也放presenter中没抽出model
MVP的契约类
~~~
public interface CascadingMenuContract {
interface View {
void setFirstMenuList(List menuList, int selectPosition);
void setSecondMenuList(List menuList);
void setThirdMenuList(List menuList);
}
interface Presenter {
void setView(CascadingMenuContract.View view);
/**
* 开始获取数据
*/
void start();
// /**
// * 第一级菜单数据
// *
// * @return
// */
// void requestFirstItem();
/**
* 第二级菜单数据
*
* @param parentMenuData
*/
void requestSecondMenuList(MenuData parentMenuData);
/**
* 第三极菜单数据
*
* @param parentMenuData
*/
void requestThirdMenuList(MenuData parentMenuData);
}
}
~~~
最终实现效果如下
看下使用
1. 用Fragment做整个弹窗的容器, 布局如下
~~~
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/half_transparent"
android:orientation="vertical">
android:id="@+id/cascadingMenuView"
android:layout_width="match_parent"
android:layout_height="@dimen/cascading_menu_max_height"
android:background="@color/transparent"
app:EMenuType="Three"
app:itemSelectedDrawableId="@drawable/choose_item_selected"
app:itemSelector="@drawable/choose_item_selector" />
</LinearLayout>
~~~
2. 初始化
~~~
cascadingMenuView =rootView.findViewById(R.id.cascadingMenuView);
//绑定Presenter
cascadingMenuView.startLoad(presenter);
//设置回调接口
cascadingMenuView.setCascadingMenuViewOnSelectListener(new MCascadingMenuViewOnSelectListener());
rootView.setOnClickListener(new View.OnClickListener() {//点击区域外退出
@Override
public void onClick(View v) {
Toast.makeText(getActivity(), "点菜单外隐藏", Toast.LENGTH_SHORT).show();
if (listener !=null) {
listener.dismissMenu();
}
}
});
~~~
3. 传入的presenter如下
~~~
private class MenuDataPresenterimplements CascadingMenuContract.Presenter {
private CascadingMenuContract.ViewmView;
public void setView(CascadingMenuContract.View mView) {
this.mView = mView;
}
@Override
public void start() {
// TODO: 这里可做异步取数据
ArrayList menuList =dBhelper.getProvince();
// TODO: 取数据完更新UI
mView.setFirstMenuList(menuList, 0);
}
@Override
public void requestSecondMenuList(MenuData parentMenuData) {
ArrayList secondMenuList =dBhelper.getCity(parentMenuData.getMenu_id());
mView.setSecondMenuList(secondMenuList);
}
@Override
public void requestThirdMenuList(MenuData parentMenuData) {
ArrayList thirdMenuList =dBhelper.getDistrict(parentMenuData.getMenu_id());
mView.setThirdMenuList(thirdMenuList);
}
}
~~~
好吧, 说多感觉就是词穷,
“Talk is cheap. Show me the code.”
网友评论