Android 继承BottomSheetDialog实现选择规格的底部弹窗

继承BottomSheetDialog实现选择规格的底部弹窗

先上效果图

img

实现思路

  • 利用BottomSheetDialog底部弹出,且可方便实现背景透明的效果,
  • 设置需要传入商品id进行查询,以及已经选中的规格下标
  • 对可能进行的操作进行方法回调
  • 使用了ButterKnife进行视图和方法绑定
  • 使用了LoadSir进行视图替换

代码

ProductCategoryDialog.class

public class ProductCategoryDialog extends BottomSheetDialog {

    @BindView(R.id.iv_close)
    ImageView ivClose;
    @BindView(R.id.riv_image)
    RoundedImageView rivImage;
    @BindView(R.id.tv_remainingAmount)
    TextView tvRemainingAmount;
    @BindView(R.id.tv_specification)
    TextView tvSpecification;
    @BindView(R.id.rv_type)
    RecyclerView rvType;
    @BindView(R.id.tv_buyNumTitle)
    TextView tvBuyNumTitle;
    @BindView(R.id.iv_reduce)
    ImageView ivReduce;
    @BindView(R.id.tv_buyNum)
    TextView tvBuyNum;
    @BindView(R.id.iv_add)
    ImageView ivAdd;
    @BindView(R.id.ll_num)
    LinearLayout llNum;
    @BindView(R.id.mb_addCar)
    MaterialButton mbAddCar;
    @BindView(R.id.content)
    ConstraintLayout content;
    @BindView(R.id.textView30)
    TextView textView30;
    @BindView(R.id.tv_product_name)
    TextView tvProductName;
    @BindView(R.id.tv_productPrice)
    TextView tvProductPrice;
    @BindView(R.id.textView32)
    TextView textView32;

    private Unbinder unbinder;
    private ProductCategoryBean categoryBean;
    private ProductCategoryAdapter categoryAdapter;
    private GoodsModel model;
    private OperateListener operateListener;
    private int stock = 0;
    private int buyNum = 1;
    private int productId;
    protected LoadService mLoadService;
    private LifecycleTransformer lifecycleTransformer;
    private Activity activity;
    private int selectIndex;

    public ProductCategoryDialog(@NonNull Activity context, LifecycleTransformer lifecycleTransformer, int productId,int selectIndex) {
        super(context);
        this.activity = context;
        this.lifecycleTransformer = lifecycleTransformer;
        this.productId = productId;
        this.selectIndex = selectIndex;
        model = new GoodsModel();
        View view = View.inflate(context, R.layout.dialog_product_category, null);
        setContentView(view);
        unbinder = ButterKnife.bind(this, view);
        //xml配置透明无效,要获取sheet控件,直接背景设置透明
        findViewById(R.id.design_bottom_sheet).setBackgroundColor(Color.TRANSPARENT); 
        //contentView是自定义的显示在BottomSheetDialog上的view
        view.post(() -> {  
            //R.id.design_bottom_sheet基本是固定的,不用担心后面API的更改
            BottomSheetBehavior behavior = BottomSheetBehavior.from(findViewById(R.id.design_bottom_sheet));
            //此处设置表示禁止BottomSheetBehavior的执行
            behavior.setHideable(false);
        });
        this.setCanceledOnTouchOutside(true);
        //setLoadSir(content);
        getCategory(productId);
    }


    public MaterialButton getMbAddCar() {
        return mbAddCar;
    }

    public void setMbAddCar(MaterialButton mbAddCar) {
        this.mbAddCar = mbAddCar;
    }

    private void initView() {
        if (rvType != null) {
            initRecyclerView();

        }
        if (categoryBean.getGoodsSpecsList().size() != 0 && categoryAdapter != null) {
            categoryAdapter.setList(categoryBean.getGoodsSpecsList());
            categoryAdapter.setSelectPosition(selectIndex);
            categoryAdapter.notifyDataSetChanged();
            seData(categoryBean.getGoodsSpecsList().get(0));
        }
    }

    private void initRecyclerView() {
        LinearLayoutManager manager = new LinearLayoutManager(getContext());
        manager.setOrientation(RecyclerView.HORIZONTAL);
        rvType.setLayoutManager(manager);
        rvType.setAdapter(categoryAdapter = new ProductCategoryAdapter(R.layout.classify_item_top_tab));
        categoryAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                ProductSpecsBean specsBean = (ProductSpecsBean) adapter.getData().get(position);
                categoryAdapter.setSelectPosition(position);
                categoryAdapter.notifyDataSetChanged();
                seData(specsBean);
                operateListener.selected(position,specsBean.getId());
            }
        });
    }


    private void seData(ProductSpecsBean productSpecsBean) {
        Glide.with(rivImage.getContext()).load(categoryBean.getGoodsDetails().getImage()).into(rivImage);
        tvProductName.setText(categoryBean.getGoodsDetails().getTitle());
        double price = productSpecsBean.getDiscountPrice();
        String integer = String.valueOf((int) price);
        int dec = (int) (price * 100) % 100;
        String decimal = dec == 0 ? "00" : String.valueOf(dec);
        SpanUtils.with(tvProductPrice)
                .append("¥")
                .setForegroundColor(Color.parseColor("#F86F57")).setFontSize(18, true)
                .append(integer)
                .setFontSize(30, true)
                .append("." + decimal)
                .setFontSize(18, true)
//                .append("/"  + "箱")
//                .setForegroundColor(Color.parseColor("#999999")).setFontSize(14, true)
                .create();
        tvRemainingAmount.setText("剩余" + productSpecsBean.getAllStock());
        stock = productSpecsBean.getAllStock();
        // TODO: 2020/12/8 规格名
        tvSpecification.setText(productSpecsBean.getUnit());

    }


    @OnClick({R.id.iv_close, R.id.mb_addCar, R.id.iv_reduce, R.id.iv_add})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_close:
                dismiss();
                break;
            case R.id.mb_addCar:
                if (categoryBean.getGoodsSpecsList().size() != 0) {
                    operateListener.addCar(categoryAdapter.getSelectPosition(), categoryBean.getGoodsDetails().getId()
                            , categoryBean.getGoodsSpecsList().get(categoryAdapter.getSelectPosition()).getId()
                            , buyNum);
                } else {
                    ToastUtils.showShort("没有商品类别");
                }

                dismiss();
                break;
            case R.id.iv_reduce:
                if (buyNum <= 1) {
                    ToastUtils.showShort("不能再减了");
                    return;
                } else {
                    buyNum--;
                    tvBuyNum.setText(buyNum + "");
                }
                break;
            case R.id.iv_add:
                if (buyNum >= stock) {
                    ToastUtils.showShort("没有更多库存");
                    return;
                } else {
                    buyNum++;
                    tvBuyNum.setText(buyNum + "");
                }
                break;
        }
    }


    private void getCategory(int id) {
        setLoadSir(content);
        HashMap hashMap = new HashMap();
        hashMap.put("goodsId", id);
        model.getGoodsSpecList(activity, hashMap, false, true, lifecycleTransformer, new ObserverResponseListener() {
            @Override
            public void onSuccess(Object o) {
                BaseResponse<ProductCategoryBean> response = (BaseResponse<ProductCategoryBean>) o;
                categoryBean = response.getData();
                initView();
                mLoadService.showSuccess();
            }

            @Override
            public void onError(ExceptionHandle.ResponeThrowable e) {
                mLoadService.showCallback(ErrorCallback.class);
            }
        });
    }


    /**
     * 注册LoadSir
     *
     * @param view 替换视图
     */

    public void setLoadSir(View view) {
        if (mLoadService == null) {
            mLoadService = LoadSir.getDefault().register(view, new Callback.OnReloadListener() {
                @Override
                public void onReload(View v) {
                    getCategory(productId);
                }
            });
        } else {
            mLoadService.showCallback(LoadingCallback.class);
        }
    }


    @Override
    public void dismiss() {
        super.dismiss();
        unbinder.unbind();
    }

    public interface OperateListener {
        void addCar(int selectPosition, int productId, int specsId, int buyNum);
        void selected(int selectPosition,int specsId);
    }

    public OperateListener getOperateListener() {
        return operateListener;
    }

    public void setOperateListener(OperateListener operateListener) {
        this.operateListener = operateListener;
    }
}

dialog_product_category.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@color/white"
        android:gravity="bottom"
        android:orientation="vertical">

        <androidx.constraintlayout.widget.ConstraintLayout
            android:id="@+id/content"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical"
            android:padding="20dp">

            <ImageView
                android:id="@+id/iv_close"
                android:layout_width="18dp"
                android:layout_height="18dp"
                android:background="@drawable/ic_1089"
                app:layout_constraintRight_toRightOf="parent"
                app:layout_constraintTop_toTopOf="parent" />


            <TextView
                android:id="@+id/textView30"
                android:layout_width="wrap_content"
                android:layout_height="match_parent"
                android:text="选择规格"
                android:textColor="@color/black_33"
                android:textSize="16sp"
                app:layout_constraintLeft_toLeftOf="parent"
                app:layout_constraintTop_toTopOf="parent" />


            <com.makeramen.roundedimageview.RoundedImageView
                android:id="@+id/riv_image"
                android:layout_width="80dp"
                android:layout_height="70dp"
                android:layout_marginTop="30dp"
                android:scaleType="centerCrop"
                app:layout_constraintLeft_toLeftOf="parent"
                app:layout_constraintTop_toBottomOf="@+id/textView30" />


            <TextView
                android:id="@+id/tv_product_name"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginLeft="20dp"
                android:ellipsize="end"
                android:maxWidth="150dp"
                android:maxLines="2"
                android:text="XXXXXX"
                android:textColor="@color/black_33"
                android:textSize="14sp"
                android:textStyle="bold"
                app:layout_constraintLeft_toRightOf="@id/riv_image"
                app:layout_constraintTop_toTopOf="@id/riv_image" />

            <TextView
                android:id="@+id/tv_productPrice"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_marginLeft="10dp"
                android:text="¥00.00"
                android:textColor="@color/red"
                android:textSize="18sp"
                android:textStyle="bold"
                app:layout_constraintBottom_toBottomOf="@+id/tv_product_name"
                app:layout_constraintEnd_toEndOf="parent"
                app:layout_constraintStart_toEndOf="@id/tv_product_name"
                app:layout_constraintTop_toTopOf="@+id/tv_product_name" />

            <TextView
                android:id="@+id/textView32"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginTop="15dp"
                android:text="已选择:"
                app:layout_constraintLeft_toLeftOf="@id/tv_productPrice"
                app:layout_constraintStart_toStartOf="@+id/tv_product_name"
                app:layout_constraintTop_toBottomOf="@+id/tv_product_name" />

            <TextView
                android:id="@+id/tv_specification"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="XXXXXXXXXXX"
                app:layout_constraintBottom_toBottomOf="@+id/textView32"
                app:layout_constraintStart_toEndOf="@+id/textView32"
                app:layout_constraintTop_toTopOf="@+id/textView32" />

            <TextView
                android:id="@+id/tv_remainingAmount"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginTop="10dp"
                android:text="剩余0"
                app:layout_constraintLeft_toLeftOf="@id/tv_productPrice"
                app:layout_constraintStart_toStartOf="@+id/textView32"
                app:layout_constraintTop_toBottomOf="@+id/textView32" />


            <androidx.recyclerview.widget.RecyclerView
                android:id="@+id/rv_type"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginTop="10dp"
                app:layout_constraintTop_toBottomOf="@id/tv_remainingAmount" />


            <TextView
                android:id="@+id/tv_buyNumTitle"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginTop="40dp"
                android:text="数量"
                android:textColor="@color/black"
                android:textSize="14sp"
                app:layout_constraintLeft_toLeftOf="parent"
                app:layout_constraintTop_toBottomOf="@id/rv_type" />

            <LinearLayout
                android:id="@+id/ll_num"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:orientation="horizontal"
                app:layout_constraintBottom_toBottomOf="@id/tv_buyNumTitle"
                app:layout_constraintRight_toRightOf="parent"
                app:layout_constraintTop_toTopOf="@id/tv_buyNumTitle">


                <ImageView
                    android:id="@+id/iv_reduce"
                    android:layout_width="20dp"
                    android:layout_height="20dp"
                    android:background="@drawable/ic_1026" />

                <TextView
                    android:id="@+id/tv_buyNum"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_marginHorizontal="10dp"
                    android:text="1"
                    android:textColor="#333333"
                    android:textSize="15sp" />


                <ImageView
                    android:id="@+id/iv_add"
                    android:layout_width="20dp"
                    android:layout_height="20dp"
                    android:layout_marginRight="5dp"
                    android:background="@drawable/ic_1027" />


            </LinearLayout>

            <com.google.android.material.button.MaterialButton
                android:id="@+id/mb_addCar"
                android:layout_width="match_parent"
                android:layout_height="50dp"
                android:layout_marginTop="25dp"
                android:text="加入购物车"
                android:textSize="15sp"
                android:theme="@style/Theme.MaterialComponents.Light"
                app:backgroundTint="@color/colorPrimary"
                app:cornerRadius="20dp"
                app:layout_constraintLeft_toLeftOf="parent"
                app:layout_constraintRight_toRightOf="parent"
                app:layout_constraintTop_toBottomOf="@id/ll_num"
                app:rippleColor="@color/white" />


        </androidx.constraintlayout.widget.ConstraintLayout>


    </LinearLayout>


</LinearLayout>

ProductCategoryAdapter.class

public class ProductCategoryAdapter extends BaseQuickAdapter<ProductSpecsBean, BaseViewHolder> {

    public int selectPosition=0;

    public ProductCategoryAdapter(int layoutResId) {
        super(layoutResId);
    }

    @Override
    protected void convert(@NotNull BaseViewHolder baseViewHolder, @Nullable ProductSpecsBean goodsSpecsListBean) {
        TextView tv_text=baseViewHolder.getView(R.id.tv_text);
        tv_text.setText(goodsSpecsListBean.getUnit());
        if(selectPosition==baseViewHolder.getLayoutPosition()){
            tv_text.setTextColor(Color.WHITE);
            tv_text.setBackgroundResource(R.drawable.shape_primary_radius15);
        }else {
            tv_text.setTextColor(Color.parseColor("#999999"));
            tv_text.setBackgroundResource(R.drawable.shape_stroke_gray_radius20);
        }
    }

    public int getSelectPosition() {
        return selectPosition;
    }

    public void setSelectPosition(int selectPosition) {
        this.selectPosition = selectPosition;
    }
}

dialog_product_category.xml 就一个TextView,没啥好写

img
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 219,589评论 6 508
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 93,615评论 3 396
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 165,933评论 0 356
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,976评论 1 295
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,999评论 6 393
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,775评论 1 307
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,474评论 3 420
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,359评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,854评论 1 317
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 38,007评论 3 338
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 40,146评论 1 351
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,826评论 5 346
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,484评论 3 331
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 32,029评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 33,153评论 1 272
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 48,420评论 3 373
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 45,107评论 2 356

推荐阅读更多精彩内容