1. 主要是自定义一个类,让其继承于popupWindow;
2. 构造函数,构造函数中的参数根据自己的需要自定义,常见的包括Context,抽象方法(用于实现这个抽象方法的时候作具体的操作);
public CaiLiaoPopup(Context context, SelectCallBack callBack, View background){ this.mContext = context; this.callBack=callBack; this.background=background; //设置可以获得焦点 setFocusable(true); //设置弹窗内可点击 setTouchable(true); //设置弹窗外可点击 setOutsideTouchable(true); //获得屏幕的宽度和高度 mScreenWidth = Tools.getScreenWidth(mContext); mScreenHeight = Tools.getScreenHeight(mContext); setBackgroundDrawable(new BitmapDrawable()); //设置弹窗的布局界面 setContentView(LayoutInflater.from(mContext).inflate(R.layout.select_multiple_view, null)); initUI(); }
3. 然后就是写适配器Adapter,由于是两级数据,因此需要两个Adapter,一个是父级,一个是子级,然后对父级的ListView设置监听,当点击某一项的时候弹出相对应的子级选项;
/** * 初始化弹窗列表 */ private void initUI(){ mListView = (ListView) getContentView().findViewById(R.id.pc_super_list); mSubListView= (ListView)getContentView().findViewById(R.id.pc_sub_list); //获取的服务器的数据 final List<GoodsType> superDatas=MetalsTypeManager.getInstance().getDatas(); final MetalsSuperAdapter superAdapter=new MetalsSuperAdapter(mContext,superDatas); mListView.setAdapter(superAdapter);
//这个是设置的第一项选项 父级是“全部”,对应的子级是“不限”
superAdapter.setSelectedPosition(0); superAdapter.notifyDataSetInvalidated(); List<GoodsTypeChild> subs=new ArrayList<GoodsTypeChild>(); GoodsTypeChild temp=new GoodsTypeChild(); temp.setName("不限"); subs.add(temp); //适配器都是常用的继承于BaseAdapter的适配器 MetalsSubAdapter subAdapter=new MetalsSubAdapter(mContext, subs); mSubListView.setAdapter(subAdapter); mSubListView.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { callBack.onSelctALL("全部商品"); dismiss(); } }); mListView.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) { superAdapter.setSelectedPosition(position); superAdapter.notifyDataSetInvalidated(); if(position==0){ List<GoodsTypeChild> subs=new ArrayList<GoodsTypeChild>(); GoodsTypeChild temp=new GoodsTypeChild(); temp.setName("不限"); subs.add(temp); MetalsSubAdapter subAdapter=new MetalsSubAdapter(mContext, subs); mSubListView.setAdapter(subAdapter); mSubListView.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { callBack.onSelctALL("全部商品"); dismiss(); } }); }else{ current_l_id=superDatas.get(position).getId(); final List<GoodsTypeChild> subs=superDatas.get(position).getChild(); MetalsSubAdapter subAdapter=new MetalsSubAdapter(mContext, subs); mSubListView.setAdapter(subAdapter); mSubListView.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { GoodsTypeChild subModle=subs.get(position); current_s_id=subModle.getId(); callBack.onSelect(subModle.getName(),current_l_id,current_s_id); dismiss(); } }); } } }); }