一个通用的popular 多选或者单选

用popularwindow实现。可以实现单选,多选。

先来个gif 代码后面贴出

一个通用的popular 多选或者单选_第1张图片
单选.gif
一个通用的popular 多选或者单选_第2张图片
多选.gif
 

import android.app.Activity;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.ColorDrawable;
import android.util.DisplayMetrics;
import android.util.SparseBooleanArray;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;

 

import java.util.ArrayList;
import java.util.List;

/**
 * create by  宋佳  on 2017/5/9 16:35 .
 * 描述 :商品中的popularWindow
 */

public class ProductPopularWindow implements PopupWindow.OnDismissListener, View.OnClickListener, AdapterView.OnItemClickListener {


    private Activity context;
    private View view;
    private PopupWindow popupWindow;
    private TextView tv_popular_cancel;
    private TextView tv_popular_ok;
    private ListView lv_popular_data;
    private LinearLayout ll_popular_buttons;
    private TextView tv_popular_title;
    private ImageView iv_popular_down;
    private PopularAdapter adapter;
    private List datas;
    private static int CHOICE_STATE = 0;

    public ProductPopularWindow(Activity context) {
        this.context = context;
        initView();
        initPopuwindow();
        initListener();
    }


    //    public static final int CHOICE_MODE_NONE = 0;  不选择
    //    public static final int CHOICE_MODE_SINGLE = 1; //单选
    //    public static final int CHOICE_MODE_MULTIPLE = 2; //多选


    private void setAdapter(View parent, int type, int[] index) {
        //items upcheck
        this.CHOICE_STATE = type;
        clearSelection();
        lv_popular_data.setChoiceMode(type);
        if (adapter == null) {
            lv_popular_data.setItemsCanFocus(false);
            adapter = new PopularAdapter(context, datas);
            lv_popular_data.setAdapter(adapter);
        }
        //liseview显示最上面
        for (int i = 0; index != null && i < index.length; i++) {
            lv_popular_data.setItemChecked(index[i], true);
        }
        lv_popular_data.setSelection(0);
        adapter.notifyDataSetChanged();
        showAsDropDown(parent);
    }

    private void initPopuwindow() {
        popupWindow = new PopupWindow(view, ViewGroup.LayoutParams.WRAP_CONTENT,
                ViewGroup.LayoutParams.WRAP_CONTENT);
        // 这个是进行设置颜色为透明
        popupWindow.setBackgroundDrawable(new ColorDrawable(
                Color.TRANSPARENT));
        popupWindow.setAnimationStyle(R.style.popular_product);
        popupWindow.setInputMethodMode(PopupWindow.INPUT_METHOD_NEEDED);
        popupWindow.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
    }

    private void initListener() {
        popupWindow.setOnDismissListener(this);
        tv_popular_cancel.setOnClickListener(this);
        tv_popular_ok.setOnClickListener(this);
        iv_popular_down.setOnClickListener(this);
        lv_popular_data.setOnItemClickListener(this);
    }

    private void initView() {
        view = LayoutInflater.from(context).inflate(R.layout.popular_products, null);
        tv_popular_cancel = (TextView) view.findViewById(R.id.tv_popular_cancel);//取消
        tv_popular_ok = (TextView) view.findViewById(R.id.tv_popular_ok);//确定
        ll_popular_buttons = (LinearLayout) view.findViewById(R.id.ll_popular_buttons);//确定  取消的 父布局
        lv_popular_data = (ListView) view.findViewById(R.id.lv_popular_data);//listView
        tv_popular_title = (TextView) view.findViewById(R.id.tv_popular_title);//标题
        iv_popular_down = (ImageView) view.findViewById(R.id.iv_popular_down);
    }

    @Override
    public void onDismiss() {
        WindowManager.LayoutParams lp = context.getWindow()
                .getAttributes();
        lp.alpha = 1f;
        context.getWindow().addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
        context.getWindow().setAttributes(lp);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tv_popular_cancel:
                //取消按钮
                popupWindow.dismiss();
                break;
            case R.id.tv_popular_ok:
                //确定按钮
                getSelectPostion();
                break;
            case R.id.iv_popular_down:
                popupWindow.dismiss();
                break;
            default:
                break;
        }
    }

    /**
     * 得到多选情况下  点击确定 选择你刚才多选的数据列表
     */
    private void getSelectPostion() {
        SparseBooleanArray checkedItems = lv_popular_data.getCheckedItemPositions();
        if (checkedItems == null || checkedItems.size() == 0) {
            return;
        }

        int arrays[] = new int[checkedItems.size()];
        for (int i = 0; i < checkedItems.size(); ++i) {
            final int position = checkedItems.keyAt(i);//点击的 position
            final boolean isChecked = checkedItems.valueAt(i);  //是否点击
            if (isChecked) {
                arrays[i] = position;
            }
        }
        popularItemOnclick.getOnItemPosition(arrays);
        popupWindow.dismiss();
    }

    /**
     * 设置标题
     *
     * @param title
     */

    public ProductPopularWindow setProductPopularTitle(String title) {
        tv_popular_title.setText(title);
        return this;
    }

    //清除状态
    private void clearSelection() {
        final int itemCount = lv_popular_data.getCount();
        for (int i = 0; i < itemCount; ++i) {
            lv_popular_data.setItemChecked(i, false);
        }
    }

    //是否隐藏下面的确定 取消按钮
    public ProductPopularWindow isHideBootomLayout(boolean isHiden) {
        if (isHiden) {
            ll_popular_buttons.setVisibility(View.GONE);
        } else {
            ll_popular_buttons.setVisibility(View.VISIBLE);
        }
        return this;
    }


    private void showAsDropDown(View parent) {
        WindowManager.LayoutParams lp = context.getWindow()
                .getAttributes();
        lp.alpha = 0.4f;
        context.getWindow().addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
        context.getWindow().setAttributes(lp);
        popupWindow.setTouchable(true);
        popupWindow.setFocusable(true);
        popupWindow.setBackgroundDrawable(new BitmapDrawable());
        popupWindow.setOutsideTouchable(true);
        changePopularSize();

        popupWindow.showAtLocation(parent, Gravity.CENTER, 0, 0);
        popupWindow.setFocusable(true);
        popupWindow.setOutsideTouchable(true);
        popupWindow.update();
    }

    //改变popular的大小
    private void changePopularSize() {
        int height_default = (int) (getScreenHeght(context) * 0.7f);
        view.measure(0, 0);
        int measuredHeight = view.getMeasuredHeight();
        int count = 0;
        int size = adapter.getCount();
        for (int i = 0; i < size; i++) {
            View childAt = adapter.getView(i, null, lv_popular_data);
            if (childAt != null) {
                childAt.measure(0, 0);
                int measuredHeight2 = childAt.getMeasuredHeight();
                count += measuredHeight2;
            }
        }
        measuredHeight += count;
        if (measuredHeight < height_default) {
            popupWindow.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
        } else {
            popupWindow.setHeight(height_default);
        }
    }

    //得到屏幕的高度
    private int getScreenHeght(Activity context) {
        DisplayMetrics dm = new DisplayMetrics();
        context.getWindowManager().getDefaultDisplay().getMetrics(dm);
        return dm.widthPixels;
    }


    /**
     * 刷新数据
     *
     * @param datas
     * @param parnent
     * @param type
     * @param indexs
     * @return
     */
    public ProductPopularWindow refreshListDatas(List datas, View parnent, int type, int[] indexs) {
        if (this.datas == null)
            this.datas = new ArrayList<>();
        this.datas.clear();
        this.datas.addAll(datas);
        setAdapter(parnent, type, indexs);
        return this;
    }


    @Override
    public void onItemClick(AdapterView parent, View view, int position, long id) {
        //当选择的模式是单选的时候 则返回它当前的id
        if (CHOICE_STATE == ListView.CHOICE_MODE_SINGLE) {
            //当只有单选模式才是可以的
            popularItemOnclick.getOnItemPosition(new int[]{position});
            popupWindow.dismiss();
            return;
        }
    }


    /**
     * 接口 点击 popular
     */
    public interface OnProductPopularItemOnclick {
        /**
         * 得到点解的postion
         *
         * @param
         */

        void getOnItemPosition(int[] positionArray);
    }

    public OnProductPopularItemOnclick popularItemOnclick;

    public void setPopularItemOnclick(OnProductPopularItemOnclick popularItemOnclick) {
        this.popularItemOnclick = popularItemOnclick;
    }
}

下面贴出popular的布局




    

        

        
    

    

    
    

    

        

        
    

    

ListView中listSelector中的代码 就是实现点击Item有个变色的效果




    
    


贴出Adapter的代码

 

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;

import com.handongkeji.customview.PopularItemLayout;
import com.handongkeji.jeno.R;
import com.handongkeji.popuwindow.model.PopularWindowBean;

import java.util.List;

/**
 * create by  宋佳  on 2017/5/10 16:57 .
 * 描述 :
 */

public class PopularAdapter extends BaseAdapter {
    private LayoutInflater inflater;
    private Context context;
    private List data;

    public PopularAdapter(Context context, List data) {
        this.context = context;
        this.data = data;
        inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    }

    @Override
    public int getCount() {
        return data.size();
    }

    @Override
    public Object getItem(int i) {
        return null;
    }

    @Override
    public long getItemId(int i) {
        return 0;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder viewHolder;
        if (convertView == null) {
            viewHolder = new ViewHolder();
            convertView = inflater.inflate(R.layout.item_popular_nomal, null);
            viewHolder.popularItemLayout = (PopularItemLayout) convertView.findViewById(R.id.rl_popular_parent);
            viewHolder.tv = (TextView) convertView.findViewById(R.id.itemCaption);
            convertView.setTag(viewHolder);
        } else {
            viewHolder = (ViewHolder) convertView.getTag();
        }
        PopularWindowBean bean = data.get(position);
        viewHolder.tv.setText(bean.getData());
        final ListView lv = (ListView) parent;
        viewHolder.popularItemLayout.setChecked(lv.isItemChecked(position));
        return convertView;
    }

    private class ViewHolder {
        private TextView tv;
        private PopularItemLayout popularItemLayout;
    }
}

item的布局代码





    

    

PopularItemLayout

 

import android.content.Context;
import android.util.AttributeSet;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Checkable;
import android.widget.RelativeLayout;

import java.util.ArrayList;
import java.util.List;

/**
 * create by  宋佳  on 2017/5/10 17:04 .
 * 描述 :自定义的popular 布局  单选或者多选
 */

public class PopularItemLayout extends RelativeLayout implements Checkable {

    /**
     * Interface definition for a callback to be invoked when the checked state of a CheckableRelativeLayout changed.
     */
    public static interface OnCheckedChangeListener {
        public void onCheckedChanged(PopularItemLayout layout, boolean isChecked);
    }

    public PopularItemLayout(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        initialise(attrs);
    }

    public PopularItemLayout(Context context, AttributeSet attrs) {
        super(context, attrs);
        initialise(attrs);
    }

    public PopularItemLayout(Context context, int checkableId) {
        super(context);
        initialise(null);
    }

    /*
     * @see android.widget.Checkable#isChecked()
     */
    public boolean isChecked() {
        return isChecked;
    }

    /*
     * @see android.widget.Checkable#setChecked(boolean)
     */
    public void setChecked(boolean isChecked) {
        this.isChecked = isChecked;
        for (Checkable c : checkableViews) {
            c.setChecked(isChecked);
        }

        if (onCheckedChangeListener != null) {
            onCheckedChangeListener.onCheckedChanged(this, isChecked);
        }
    }

    /*
     * @see android.widget.Checkable#toggle()
     */
    public void toggle() {
        this.isChecked = !this.isChecked;
        for (Checkable c : checkableViews) {
            c.toggle();
        }
    }

    public void setOnCheckedChangeListener(OnCheckedChangeListener onCheckedChangeListener) {
        this.onCheckedChangeListener = onCheckedChangeListener;
    }

    @Override
    protected void onFinishInflate() {
        super.onFinishInflate();

        final int childCount = this.getChildCount();
        for (int i = 0; i < childCount; ++i) {
            findCheckableChildren(this.getChildAt(i));
        }
    }

    /**
     * Read the custom XML attributes
     */
    private void initialise(AttributeSet attrs) {
        this.isChecked = false;
        this.checkableViews = new ArrayList(5);
    }

    /**
     * Add to our checkable list all the children of the view that implement the interface Checkable
     */
    private void findCheckableChildren(View v) {
        if (v instanceof Checkable) {
            this.checkableViews.add((Checkable) v);
        }

        if (v instanceof ViewGroup) {
            final ViewGroup vg = (ViewGroup) v;
            final int childCount = vg.getChildCount();
            for (int i = 0; i < childCount; ++i) {
                findCheckableChildren(vg.getChildAt(i));
            }
        }
    }

    private boolean isChecked;
    private List checkableViews;
    private OnCheckedChangeListener onCheckedChangeListener;
}

InertCheckBox

public class InertCheckBox extends CheckBox {
    // Provide the same constructors as the superclass
    public InertCheckBox(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    // Provide the same constructors as the superclass
    public InertCheckBox(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    // Provide the same constructors as the superclass
    public InertCheckBox(Context context) {
        super(context);
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        // Make the checkbox not respond to any user event  使复选框不响应任何用户事件
        return false;
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        // Make the checkbox not respond to any user event
        return false;
    }

    @Override
    public boolean onKeyMultiple(int keyCode, int repeatCount, KeyEvent event) {
        // Make the checkbox not respond to any user event
        return false;
    }

    @Override
    public boolean onKeyPreIme(int keyCode, KeyEvent event) {
        // Make the checkbox not respond to any user event
        return false;
    }

    @Override
    public boolean onKeyShortcut(int keyCode, KeyEvent event) {
        // Make the checkbox not respond to any user event
        return false;
    }

    @Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {
        // Make the checkbox not respond to any user event
        return false;
    }

    @Override
    public boolean onTrackballEvent(MotionEvent event) {
        // Make the checkbox not respond to any user event
        return false;
    }

使用的方法

多选

  //弹出数据
                final List list = new ArrayList<>();
                for (int i = 0; i < 30; i++) {
                    PopularWindowBean bean = new PopularWindowBean();
                    bean.setId(i);
                    bean.setData(new Random().nextInt() + "");
                    list.add(bean);
                }
                ProductPopularWindow p = new ProductPopularWindow(getActivity());
                p.setProductPopularTitle("demo多选").refreshListDatas(list, view, ListView.CHOICE_MODE_MULTIPLE, null).setPopularItemOnclick(new ProductPopularWindow.OnProductPopularItemOnclick() {
                    @Override
                    public void getOnItemPosition(int[] positionArray) {
                        for (int i = 0; i < positionArray.length; i++) {
                            Log.i("数据", "getOnItemPosition:" + list.get(positionArray[i]).getData());
                        }
                    }
                });

单选

popularWindow.setProductPopularTitle("请选择职业").isHideBootomLayout(true).refreshListDatas(list_industry, v, ListView.CHOICE_MODE_SINGLE, array_Industry).setPopularItemOnclick(new ProductPopularWindow.OnProductPopularItemOnclick() {
                        @Override
                        public void getOnItemPosition(int[] positionArray) {
                            array_Industry = positionArray;
                            text_worker_one.setText(list_industry.get(positionArray[0]).getData());
                            //清空小行业
                            text_woek_two.setText("");
                            array_Industry_small = null;
                            String code = list_industry.get(positionArray[0]).getCodeString();
                            initSmallIndustry(code);
                        }
                    });

你可能感兴趣的:(一个通用的popular 多选或者单选)