AppCompatDialogFragment自定义模态弹框

很多时候系统自带的AlertDialog并不能满足我们模态弹框的需求,我们的app具体业务可能需要定制化的模态弹框,这个时候我们可以通过继承AppCompatDialogFragment来定制化开发我们需要的模态弹框。

现在大家看看威哥在威哥开发的《妙生活自助称重》App上的继承自AppCompatDialogFrament的定制化弹框效果图:

AppCompatDialogFragment自定义模态弹框_第1张图片

童鞋们,怎么样?威哥做出来的效果还不错吧。

废话少说,直接上代码,和大家一起分享分享,之后大家就可以自行动手了:

1.xml布局(addfruit_dialog_layout.xml):





    

        

        

        

        

        


        

        


        


        
        
        

            

2、自定义弹框java类:

package com.msh.mshselfweighing.app;

import android.app.Dialog;
import android.content.DialogInterface;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.FragmentManager;
import android.support.v7.app.AppCompatDialogFragment;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.style.ForegroundColorSpan;
import android.text.style.StrikethroughSpan;
import android.text.style.UnderlineSpan;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.msh.mshselfweighing.MainApplication;
import com.msh.mshselfweighing.R;
import com.msh.mshselfweighing.dto.Category.SelfWeightProductCategoryDto;
import com.msh.mshselfweighing.dto.Product.SelfWeightProductInfoDto;
import com.msh.mshselfweighing.modelinfo.MachineBaseInfo;

import java.math.BigDecimal;
import java.text.DecimalFormat;

/**
 * 商品模态框
 * Author:William(徐威)
 * Create Time:2018-09-10
 */
public class AddProductDialogFragment extends AppCompatDialogFragment implements View.OnClickListener {
    private Button btnCancel;
    private Button btnAdd;
    private TextView tvDes;
    private TextView tvPrice;
    private TextView tvQuality;
    private TextView tvTotal;
    private ImageView ivLogo;
    private DecimalFormat decimalFormat = new DecimalFormat("0.00");
    private DecimalFormat weightFormat = new DecimalFormat("0.000");
    private BigDecimal price;
    private String name;
    boolean isShow = false;//防多次点击
    private SelfWeightProductInfoDto buyProductModel;//选择商品对象
    private TextView tv_addfruit_ProductUnit;   //单价标签
    private TextView tv_addfruit_weightUnit;    //重量标头

    //构造函数
    public AddProductDialogFragment() {
        super();
    }

    @Override
    public void onStart() {
        super.onStart();
        Dialog dialog = getDialog();
        dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        dialog.setCanceledOnTouchOutside(true);
        //dialog.setCancelable(false);
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.addfruit_dialog_layout, container, false);
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        initView(view);
        initAction();

        //初始化视图
        Bundle bundle = getArguments();
        buyProductModel = (SelfWeightProductInfoDto) bundle.getSerializable("productModel");
        initData();
    }

    /**
     * 初始化视图
     * Author:William(徐威)
     * Create Time:2018-09-11
     *
     * @param view
     */
    private void initView(View view) {
        btnAdd = view.findViewById(R.id.btn_add);
        btnCancel = view.findViewById(R.id.btn_cancel);
        tvDes = view.findViewById(R.id.tv_des);
        tvPrice = view.findViewById(R.id.tv_price);
        tvQuality = view.findViewById(R.id.tv_quality);
        tvTotal = view.findViewById(R.id.tv_total);
        ivLogo = view.findViewById(R.id.iv_logo);
        tv_addfruit_ProductUnit = view.findViewById(R.id.tv_addfruit_ProductUnit);
        tv_addfruit_weightUnit = view.findViewById(R.id.tv_addfruit_weightUnit);

        tvQuality.setAlpha(0.5f);
    }

    /**
     * 初始化注册事件
     * Author:William(徐威)
     * Create Time:2018-09-11
     */
    private void initAction() {
        btnAdd.setOnClickListener(this);
        btnCancel.setOnClickListener(this);
        btnAdd.setEnabled(false);
        getDialog().setOnKeyListener(new DialogInterface.OnKeyListener() {
            @Override
            public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
                return true;
            }
        });
    }

    /**
     * 初始化数据
     * Author:William(徐威)
     * Create Time:2018-09-11
     */
    private void initData() {
        if (buyProductModel != null) {
            //会员价和门店价保留2位四舍五入
            buyProductModel.setCurrentPrice(buyProductModel.getCurrentPrice().setScale(2, BigDecimal.ROUND_HALF_UP));
            buyProductModel.setStockCurrentPrice(buyProductModel.getStockCurrentPrice().setScale(2, BigDecimal.ROUND_HALF_UP));

            tv_addfruit_ProductUnit.setText(String.format("单价(元/%s)", buyProductModel.getDenominatedUnit()));
            tv_addfruit_weightUnit.setText(String.format("计重(%s)", buyProductModel.getDenominatedUnit()));
            name = buyProductModel.getProductName();
            price = buyProductModel.getCurrentPrice();
            tvDes.setText(buyProductModel.getProductName());

            //价格
            String strPrice = String.format("%s/%s", decimalFormat.format(buyProductModel.getStockCurrentPrice()), decimalFormat.format(price));
            SpannableString spanPrice = new SpannableString(strPrice);
            spanPrice.setSpan(new ForegroundColorSpan(Color.parseColor("#c0c0c0")), 0, decimalFormat.format(buyProductModel.getStockCurrentPrice()).length() + 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
            spanPrice.setSpan(new StrikethroughSpan(), 0, decimalFormat.format(buyProductModel.getStockCurrentPrice()).length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
            spanPrice.setSpan(new ForegroundColorSpan(Color.parseColor("#333333")), decimalFormat.format(buyProductModel.getStockCurrentPrice()).length() + 1, strPrice.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
            tvPrice.setText(spanPrice);

            BigDecimal totalAmt = (new BigDecimal(1)).multiply(price);
            BigDecimal totalStoreAmt = (new BigDecimal(1)).multiply(buyProductModel.getStockCurrentPrice());
            tvQuality.setText("1");

            Glide.with(getActivity()).load(buyProductModel.getImageUrl())    //加载地址
                    .placeholder(R.drawable.productlaoding)  //加载未完成时显示占位图
                    .error(R.drawable.productloadfailed)
                    .into(ivLogo);
            buyProductModel.setV_BuyNumKg(new BigDecimal(1));
            buyProductModel.setV_BuyNumJin(new BigDecimal(1));
            buyProductModel.setV_BuyTotalAmt(price);
            buyProductModel.setV_BuyMemberTotalAmt(price);

            if (MainApplication.ProductWeightJin != null && MainApplication.ProductWeightJin.length() > 0
                    && buyProductModel.isWeight()) {
                btnAdd.setEnabled(true);
                tvTotal.setAlpha(1);
                tvQuality.setAlpha(1);
                btnAdd.setAlpha(1);
                btnCancel.setAlpha(1);
                tvQuality.setText(MainApplication.ProductWeightJin);
                totalAmt = (new BigDecimal(MainApplication.ProductWeightJin)).multiply(price).setScale(2, BigDecimal.ROUND_HALF_UP);
                totalStoreAmt = (new BigDecimal(MainApplication.ProductWeightJin)).multiply(buyProductModel.getStockCurrentPrice()).setScale(2, BigDecimal.ROUND_HALF_UP);

                BigDecimal storePrice = buyProductModel.getStockCurrentPrice();
                BigDecimal storeProductAmt = storePrice.multiply(new BigDecimal(MainApplication.ProductWeightJin)).setScale(2, BigDecimal.ROUND_HALF_UP);
                buyProductModel.setV_BuyNumKg(new BigDecimal(MainApplication.ProductWeight));
                buyProductModel.setV_BuyNumJin(new BigDecimal(MainApplication.ProductWeightJin));
                buyProductModel.setV_BuyTotalAmt(storeProductAmt);
                buyProductModel.setV_BuyMemberTotalAmt(storeProductAmt);
            }

            //总价
            String strTotalAmt = String.format("%s/%s", decimalFormat.format(totalStoreAmt), decimalFormat.format(totalAmt));
            SpannableString spanTotalAmt = new SpannableString(strTotalAmt);
            spanTotalAmt.setSpan(new ForegroundColorSpan(Color.parseColor("#c0c0c0")), 0, decimalFormat.format(totalStoreAmt).length() + 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
            spanTotalAmt.setSpan(new StrikethroughSpan(), 0, decimalFormat.format(totalStoreAmt).length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
            spanTotalAmt.setSpan(new ForegroundColorSpan(Color.parseColor("#D90909")), decimalFormat.format(totalStoreAmt).length() + 1, strTotalAmt.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
            tvTotal.setText(spanTotalAmt);
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_cancel:
                //取消按钮
                dismiss();
                break;
            case R.id.btn_add:
                //添加按钮
                if (listener != null) {
                    listener.onAddProduct(buyProductModel);
                }
                dismiss();
                break;
            default:
                break;
        }
    }

    /**
     * 更新重量
     * Author:William(徐威)
     * Create Time:2018-09-12
     */
    public void update(int status) {
        if (buyProductModel != null && (status == 1 || buyProductModel.getV_BuyNumKg().compareTo(new BigDecimal(MainApplication.ProductWeight)) != 0)) {
            initData();
        }
    }

    @Override
    public void show(FragmentManager manager, String tag) {
        if (isShow) {
            return;
        }
        super.show(manager, tag);
        isShow = true;
    }

    @Override
    public void dismiss() {
        super.dismiss();
        isShow = false;
    }

    private AddListener listener = null;

    public void setListener(AddListener listener) {
        this.listener = listener;
    }

    /**
     * 申明监听接口
     * Author:William(徐威)
     * Create Time:2018-09-12
     */
    public interface AddListener {
        //添加商品事件
        void onAddProduct(SelfWeightProductInfoDto buyProductModel);
    }
}

3、调用:

public static AddProductDialogFragment dialogFragment = null; //添加商品弹框
IndexActivity.dialogFragment = new AddProductDialogFragment();
IndexActivity.dialogFragment.setListener(new AddProductDialogFragment.AddListener() {
    //重写添加商品事件
    @Override
    public void onAddProduct(SelfWeightProductInfoDto buyProductModel) {
        Toast.makeText(mContext,buyProductModel.getProductName(),Toast.LENGTH_LONG).show();
    }
});

MainApplication.IsWeight = model.isWeight();
Bundle bundle = new Bundle();
bundle.putSerializable("productModel", model);
IndexActivity.dialogFragment.setArguments(bundle);
IndexActivity.dialogFragment.show(getFragmentManager(), "AddProductDialogFragment");

 

你可能感兴趣的:(Android,Java)