一個通用的popular 多選或者單選

用popularwindow實現。可以實現單選,多選。

先來個gif 代碼后面貼出

單選.gif
多選.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<PopularWindowBean> 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<PopularWindowBean> 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的布局

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@drawable/list_popu_bg"
    android:orientation="vertical"
    android:paddingLeft="14dp"
    android:paddingRight="14dp">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="center_vertical"
        android:orientation="horizontal"
        android:paddingBottom="5dp"
        android:paddingTop="5dp"
        >

        <TextView
            android:id="@+id/tv_popular_title"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_gravity="center_vertical"
            android:layout_weight="9"
            android:background="@drawable/popu_title_bg"
            android:gravity="center"
            android:text=""
            android:textColor="@color/text_color_6"
            android:textSize="16sp"/>

        <ImageView
            android:id="@+id/iv_popular_down"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_gravity="center_vertical"
            android:layout_weight="1"
            android:src="@android:drawable/ic_delete"
            />
    </LinearLayout>

    <View
        android:layout_width="match_parent"
        android:layout_height="1dp"
        android:layout_marginBottom="5dp"
        android:layout_marginLeft="25dp"
        android:layout_marginRight="25dp"
        android:layout_marginTop="5dp"
        android:background="#f0f0f0"
        ></View>

    <ListView
        android:id="@+id/lv_popular_data"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"
        android:cacheColorHint="#00000000"
        android:divider="#f0f0f0"
        android:dividerHeight="1dp"
        android:listSelector="@drawable/bg_all_select"
        android:scrollbars="none">
    </ListView>

    <LinearLayout
        android:id="@+id/ll_popular_buttons"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginLeft="20dp"
        android:layout_marginRight="20dp"
        android:background="@drawable/act_input_bg1"
        android:gravity="center"
        android:orientation="horizontal"
        android:paddingBottom="5dp"
        android:paddingTop="5dp"
        >

        <TextView
            android:id="@+id/tv_popular_cancel"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_marginRight="10dp"
            android:layout_weight="1"
            android:background="@drawable/list_popu_btn_selector"
            android:gravity="center"
            android:paddingBottom="5dp"
            android:paddingTop="5dp"
            android:text="取消"
            android:textColor="@color/text_color_6"
            android:textSize="16sp"/>

        <TextView
            android:id="@+id/tv_popular_ok"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_marginLeft="10dp"
            android:layout_weight="1"
            android:background="@drawable/list_popu_btn_selector"
            android:gravity="center"
            android:paddingBottom="5dp"
            android:paddingTop="5dp"
            android:text="確定"
            android:textColor="@color/text_color_6"
            android:textSize="16sp"/>
    </LinearLayout>

    <View
        android:layout_width="match_parent"
        android:layout_height="10dp"/>
</LinearLayout>

ListView中listSelector中的代碼 就是實現點擊Item有個變色的效果

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">

    <item android:drawable="@drawable/bg_press" android:state_pressed="false" android:state_window_focused="false"/>
    <item android:drawable="@drawable/bg_unpress" android:state_pressed="true" android:state_window_focused="true"/>

</selector>

貼出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<PopularWindowBean> data;

    public PopularAdapter(Context context, List<PopularWindowBean> 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的布局代碼

<?xml version="1.0" encoding="utf-8"?>
<com.xxxxx.PopularItemLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/rl_popular_parent"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    >


    <TextView
        android:id="@+id/itemCaption"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerVertical="true"
        android:focusable="false"
        android:paddingBottom="5dp"
        android:paddingTop="5dp"
        android:paddingLeft="5dp"
        android:text="對對對"
        android:textColor="@color/text_color_6"
        android:textSize="14sp"/>

    <com.xxxx.customview.InertCheckBox
        android:id="@+id/itemCheckBox"
        style="@style/CustomCheckBox"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:layout_centerVertical="true"
        android:layout_marginRight="5dp"
        android:focusable="false"
        />
</com.xxxx.PopularItemLayout>

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<Checkable>(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<Checkable> 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<PopularWindowBean> 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);
                        }
                    });
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容