自定义的弹出框列表适配器,类似于大众点评或美团

无意下载一个代码, 还不错,记录一下,说不定以后会用到.效果图如下

整体工程是引入了一个library,当然完全可以写到一个工程里面,如下截图

代码还是很好理解的, 下面贴出来,顺便又加了一些注释

1.MainActivity.java

public class MainActivity extends ActionBarActivity {
    private PopupButton btn;
    private PopupButton btn2;
    private LayoutInflater inflater;
    private List<String> cValues;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        btn = (PopupButton) findViewById(R.id.btn);
        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);

        View view2 = inflater.inflate(R.layout.popup2,null);
        ListView pLv = (ListView) view2.findViewById(R.id.parent_lv);
        final ListView cLv = (ListView) view2.findViewById(R.id.child_lv);
        List<String> pList = new ArrayList<>();
        final List<List<String>> cList = new ArrayList<>();
        for(int i = 0; i < 10; i ++) {
            pList.add("p" + i);
            List<String> t = new ArrayList<>();
            for(int j = 0; j < 15; j++) {
                t.add(pList.get(i) + "-c" + j);
            }
            cList.add(t);
        }

        cValues = new ArrayList<>();
        cValues.addAll(cList.get(0));
        final PopupAdapter pAdapter = new PopupAdapter(this,R.layout.popup_item,pList,R.drawable.normal,R.drawable.press2);
        final PopupAdapter cAdapter = new PopupAdapter(this,R.layout.popup_item,cValues,R.drawable.normal,R.drawable.press);
        pAdapter.setPressPostion(0);//设置默认显示第一个数据

        pLv.setAdapter(pAdapter);
        cLv.setAdapter(cAdapter);

        pLv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                pAdapter.setPressPostion(position);
                pAdapter.notifyDataSetChanged();
                cValues.clear();//每次点击父 adapter,要清空一下子adapter,否则会数据混乱
                cValues.addAll(cList.get(position));
                cAdapter.notifyDataSetChanged();
                cAdapter.setPressPostion(-1);
                cLv.setSelection(0);
            }
        });

        cLv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                cAdapter.setPressPostion(position);
                cAdapter.notifyDataSetChanged();
                btn2.setText(cValues.get(position));
                btn2.hidePopup();
            }
        });
        btn2 = (PopupButton) findViewById(R.id.btn2);
        btn2.setPopupView(view2);
    }

}

activity_main.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:popupbtn="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal"
    tools:context=".MainActivity">

    <pw.h57.popupbuttonlibrary.PopupButton
        android:id="@+id/btn"
        android:layout_width="0dp"
        android:layout_weight="1"
        android:layout_height="wrap_content"
        android:text="按钮1"
        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"
        />
    <pw.h57.popupbuttonlibrary.PopupButton
        android:id="@+id/btn2"
        android:layout_width="0dp"
        android:layout_weight="1"
        android:layout_height="wrap_content"
        android:text="按钮2"
        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"
        />
</LinearLayout>

对应的popup.xml 和popup2.xml分别如下

<?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>
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal" android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@android:color/white"
    >
    <ListView
        android:id="@+id/parent_lv"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:scrollbars="none"
        android:layout_weight="1"></ListView>
    <View
        android:layout_width="1dp"
        android:layout_height="match_parent"
        android:background="@android:color/darker_gray"/>
    <ListView
        android:id="@+id/child_lv"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="1"></ListView>
</LinearLayout>

2.下面是library代码

首先是adapter---PopupAdapter

public class PopupAdapter extends ArrayAdapter<String> {
    private int resource;
    private int normalBg;
    private int pressBg;
    private int selection;

    public PopupAdapter(Context context, int resource, String[] objects, int normalBg, int pressBg) {
        super(context, resource, objects);
        initParams(resource, normalBg, pressBg);
    }

    public PopupAdapter(Context context, int resource, List<String> objects, int normalBg, int pressBg) {
        super(context, resource, objects);
        initParams(resource, normalBg, pressBg);
    }

    private void initParams(int resource, int normalBg, int pressBg){
        this.resource = resource;
        this.normalBg = normalBg;
        this.pressBg = pressBg;
        this.selection = -1;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        String s = getItem(position);
        View view;
        ViewHolder holder;
        if(convertView == null) {
            view = LayoutInflater.from(getContext()).inflate(resource,null);
            holder = new ViewHolder();
            holder.tv = (TextView) view.findViewById(R.id.tv);
            view.setTag(holder);
        } else {
            view = convertView;
            holder = (ViewHolder) view.getTag();
        }
        holder.tv.setText(s);
        if(position == selection) {
            holder.tv.setBackgroundResource(pressBg);
        } else {
            holder.tv.setBackgroundResource(normalBg);
        }
        return view;
    }

    public void setPressPostion(int position) {
        this.selection = position;
    }
    class ViewHolder{
        TextView tv;
    }
}

PopupButtonListener接口如下

public interface PopupButtonListener {
    public void onShow();
    public void onHide();
}

下面是自定义popupButton

public class PopupButton extends Button implements PopupWindow.OnDismissListener {
    private int normalBg;//正常状态下的背景
    private int pressBg;//按下状态下的背景
    private int normalIcon;//正常状态下的图标
    private int pressIcon;//按下状态下的图标
    private PopupWindow popupWindow;
    private Context context;
    private int screenWidth;
    private int screenHeight;
    private int paddingTop;
    private int paddingLeft;
    private int paddingRight;
    private int paddingBottom;
    private PopupButtonListener listener;

    public PopupButton(Context context) {
        super(context);
        this.context = context;
    }

    public PopupButton(Context context, AttributeSet attrs) {
        super(context, attrs);
        this.context = context;
        initAttrs(context, attrs);
        initBtn(context);
    }

    public PopupButton(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        this.context = context;
    }

    //初始化各种自定义参数
    private void initAttrs(Context context, AttributeSet attrs) {
        TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.popupbtn);

        normalBg = typedArray.getResourceId(R.styleable.popupbtn_normalBg, -1);
        pressBg = typedArray.getResourceId(R.styleable.popupbtn_pressBg, -1);
        normalIcon = typedArray.getResourceId(R.styleable.popupbtn_normalIcon, -1);
        pressIcon = typedArray.getResourceId(R.styleable.popupbtn_pressIcon, -1);
    }

    /**
     * 初始话各种按钮样式
     */
    private void initBtn(final Context context) {
        //获取当前按钮 内边距
        paddingTop = this.getPaddingTop();
        paddingLeft = this.getPaddingLeft();
        paddingRight = this.getPaddingRight();
        paddingBottom = this.getPaddingBottom();
        setNormal();

        //获取当前屏幕宽高
        WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        screenWidth = wm.getDefaultDisplay().getWidth();
        screenHeight = wm.getDefaultDisplay().getHeight();
    }

    /**
     * 设置正常模式下的按钮状态
     */
    private void setNormal() {
        if (normalBg != -1) {//表示当前资源id存在
            this.setBackgroundResource(normalBg);//设置button背景色
            this.setPadding(paddingLeft,paddingTop,paddingRight,paddingBottom);//设置padding值
        }
        if (normalIcon != -1) {
            Drawable drawable = getResources().getDrawable(normalIcon);
            //设置图片资源的 这一步必须要做,否则不会显示. 指定一个矩形边界
            drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
            //将图片资源设置到 button上面
            this.setCompoundDrawables(null, null, drawable, null);
        }
    }

    /**
     * 隐藏弹出框
     */
    public void hidePopup(){
        if(popupWindow != null && popupWindow.isShowing()) {
            popupWindow.dismiss();
        }
    }

    /**
     * 设置自定义接口
     * @param listener
     */
    public void setListener(PopupButtonListener listener) {
        this.listener = listener;
    }

    /**
     * 设置popupwindow的view
     * @param view
     */
    public void setPopupView(final View view) {
        this.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if(popupWindow == null) {
                    LinearLayout layout = new LinearLayout(context);
                    LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, (int) (screenHeight * 0.6));
                    view.setLayoutParams(params);//把该参数作用到 view上面,view具备了 宽度铺满屏幕,高度是屏幕的60%
                    layout.addView(view);//把view加入到线性布局中
                    layout.setBackgroundColor(Color.argb(60, 0, 0, 0));//设置该线性为黑色,透明度为60 -->浅灰色
                    popupWindow = new PopupWindow(layout,screenWidth,screenHeight);
                    popupWindow.setFocusable(true);//可以获取焦点
                    popupWindow.setBackgroundDrawable(new BitmapDrawable());//设置背景
                    //要想按返回键back,收起 popupWindow --必须设置上面 的2行代码
                    popupWindow.setOutsideTouchable(true);//要想触摸外部(或者点击popup的item)可以收起popupwindow,也必须用到上面2行代码
                    popupWindow.setOnDismissListener(PopupButton.this);
                    layout.setOnClickListener(new OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            popupWindow.dismiss();
                        }
                    });
                }
                if(listener != null) {
                    listener.onShow();
                }
                setPress();
                //设置popupwindow位于 view的左下方显示== showAsDropDown(PopupButton.this,0,0);
                popupWindow.showAsDropDown(PopupButton.this);
            }
        });
    }

    /**
     * 设置选中时候的按钮状态
     */
    private void setPress() {
        if (pressBg != -1) {
            this.setBackgroundResource(pressBg);
            this.setPadding(paddingLeft,paddingTop,paddingRight,paddingBottom);
        }
        if (pressIcon != -1) {
            Drawable drawable = getResources().getDrawable(pressIcon);
            /// 这一步必须要做,否则不会显示.
            drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
            this.setCompoundDrawables(null, null, drawable, null);
        }
    }

    @Override
    public void onDismiss() {
        setNormal();
        if(listener != null) {
            listener.onHide();
        }
    }
}

popup_item.xml布局文件

<?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">
    <TextView
        android:id="@+id/tv"
        android:padding="8dp"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />
</LinearLayout>

attrs.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <declare-styleable name="popupbtn">
        <!-- 正常状态下的背景 -->
        <!--reference 是对资源id的引用-->
        <attr name="normalBg" format="reference" />
        <!-- 按下状态下的背景 -->
        <attr name="pressBg" format="reference" />
        <!-- 正常状态下的图标 -->
        <attr name="normalIcon" format="reference" />
        <!-- 按下状态下的图标 -->
        <attr name="pressIcon" format="reference" />
        <!-- 按钮的padding -->

    </declare-styleable>
</resources>

以上就是全部代码了.

时间: 2024-10-19 13:26:07

自定义的弹出框列表适配器,类似于大众点评或美团的相关文章

自定义PopupWindow弹出框(带有动画)

使用PopupWindow来实现弹出框,并且带有动画效果 首先自定义PopupWindow 1 public class LostPopupWindow extends PopupWindow { 2 public Lost lost; 3 public void onLost(Lost lost){ 4 this.lost = lost; 5 } 6 private View conentView; 7 8 public View getConentView() { 9 return cone

自定义PobUpwindow弹出框

在做分享这一块的时候,用到弹出框的功能,还必须得有点击返回键,同样可以撤销显示的弹出框,于是自己就动手写了一个,一切看代码: public class ShareBoardPicker implements OnClickListener { private Context mContext; private SharePobupWindow mPopupWindow;//分享框 private LinearLayout layout; private RelativeLayout mWeixi

自定义popup弹出框

ys_popup.css .ys-popup{     position:fixed;     top:0;     bottom:0;     left:0;     right:0;     display:none;     z-index: 99999;     background-color: rgba(0,0,0,0.4); } .ys-popup .ys-popup-content{     position:absolute;     left:30px;     right:

iOS自定义提示弹出框(类似UIAlertView)

菜鸟一枚,大神勿喷.自己在牛刀小试的时候,发现系统的UIAlertView有点不喜欢,然后就自己自定义了一个UIAlertView,基本上实现了系统的UIAlertView,可以根据项目的需求修改UIAlertView的颜色.欢迎大神多多指导.不胜感激! 效果图: Paste_Image.png --------------直接贴代码---------不喜勿喷----------大神多多指导.不胜感激!------- #import <UIKit/UIKit.h> typedef void(^

swing自定义JDialog弹出框

第一次搞swing,自定义JDialog的例子较少,写下来备忘 ,对JDialog中的文本框进行了验证 package com.chauvet; import java.awt.Component;import java.awt.Dimension;import java.awt.Toolkit;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import java.awt.event.KeyEvent

ionic中自定义底部弹出框

通用部分:<script>     MY_FUNCTION = (function() {        var upSheet = document.createElement('div');        upSheet.setAttribute('style', 'display:none;position:absolute;left:0px;top:0px;z-index: 9999;');        upSheet.style.width = document.documentE

自定义弹出框效果

对网站而言,弹出框是比较常见的.或是给出用户操作提示,或是通过弹出框打开一个小窗口以提示信息,或是给出错误警示等等. 但是由于浏览器自带的弹出窗口alert , confirm , prompt样式比较单调,且不同浏览器有不同的默认样式设置. 所以在日常工作中,给网站做一个自定义的弹出框十分必要.特别是富交互的网站 一.提示框 html部分: 1 <!--修改弹窗--> 2 <div class="pop-alert" id="pop" style

AlertDialog自定义View的用法+如何改变弹出框的大小

android系统定义了弹出框,支持我们自定义布局: public AlertDialog getEditCustomDialog() { LayoutInflater inflater = getLayoutInflater(); View view = inflater.inflate(R.layout.custom_message_rename, null); AlertDialog.Builder builder = new AlertDialog.Builder(AnimationTe

鼠标拖动 自定义弹出框

/*设置自定义弹出框可移动*/jQuery(document).ready( function () { $('.popmodal .popheader').mousedown( function (event) { var isMove = true; var abs_x = event.pageX - $(this).offset().left; var abs_y = event.pageY - $(this).offset().top; $(document).mousemove(fun