
最近公司再做新的项目其中有一个功能类似于大众点评或者美团的分类筛选,之前也在网上找过一些类似的东西,可是效果都跟我们想要的有一些差别,而且以前也弄过但是那时候很懒 都是直接一段代码写进去,最近发现复用性太差了,每次都要写好长一段代码,于是就有了现在的这个项目,封装成了一个控件,用的时候直接写进去就可以了,简单了很多,效果就跟图片的效果是一样的。
用的时候首先在布局文件中写入我们的控件
- <pw.h57.popupbuttonlibrary.PopupButton
- android:id="@+id/btn"
- android:layout_width="0dp"
- android:layout_weight="1"
- android:layout_height="wrap_content"
- android:text="啦啦啦"
- android:textSize="20dp"
- popupbtn:normalBg="@drawable/tab_bkg_line"
- popupbtn:normalIcon="@drawable/arrow_down_shop"
- popupbtn:pressBg="@drawable/tab_bkg_selected"
- popupbtn:pressIcon="@drawable/arrow_up_shop"
- />
复制代码 然后在写一个用于弹出显示的布局 - <?xml version="1.0" encoding="utf-8"?>
- <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
- android:orientation="vertical" android:layout_width="match_parent"
- android:layout_height="match_parent">
- <ListView
- android:id="@+id/lv"
- android:layout_width="match_parent"
- android:layout_height="match_parent"
- android:gravity="center"
- android:background="#fff"/>
- </LinearLayout>
复制代码 最后在activity文件中绑定控件并把view放入到控件中即可,如下 - PopupButton btn = (PopupButton) findViewById(R.id.btn);
- LayoutInflater inflater = LayoutInflater.from(this);
- View view = inflater.inflate(R.layout.popup,null);
- ListView lv = (ListView) view.findViewById(R.id.lv);
- final String[] arr = {"item01","item02","item03","item04","item05","item06","item07","item08","item09","item10"};
- final PopupAdapter adapter = new PopupAdapter(this,R.layout.popup_item,arr,R.drawable.normal,R.drawable.press);
- lv.setAdapter(adapter);
- lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
- @Override
- public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
- adapter.setPressPostion(position);
- adapter.notifyDataSetChanged();
- btn.setText(arr[position]);
- btn.hidePopup();
- }
- });
- btn.setPopupView(view);
复制代码 这样就做到了图中左侧按钮的效果了,怎么样很简单吧,代码中的popupAdapter在源码中也都提供了,如果不想自定义直接用那个就可以了 最后欢迎反馈bug 所有的东西都在github中有提供,app文件夹就是demo,libaray文件夹就是控件,是基于as的项目,eclipse直接拷贝文件就可以直接用了 github: https://github.com/crazyhl/PopupButton