安卓—自定义 AlertDialog 的样式

自定义修改安卓弹出框的样式

效果图:

安卓—自定义 AlertDialog 的样式_第1张图片

 

 

1.在style.xml下添加


    

 2.在主体配置里引入自定义的AlertDialog主题

安卓—自定义 AlertDialog 的样式_第2张图片

3.java代码写法

/**
     * 默认的弹出窗口
     * @param view
     */
    public void alertDialog(View view) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("弹出窗");
        builder.setMessage("提示信息!");
        builder.setPositiveButton("确认", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                System.out.println("确认执行函数");
            }
        }).setNegativeButton("取消", null);
        builder.show();
    }

    /**
     * 自定义样式的弹出窗
     * @param view
     */
    public void alertDialog2(View view) {
        final AlertDialog.Builder builder = new AlertDialog.Builder(this);
        // 自定义 title样式
        TextView title = new TextView(this);
        title.setText("自定义弹出窗");
        title.setTextSize(24);
        title.setGravity(Gravity.CENTER);
        title.setPadding(0,20,0,20);
        builder.setCustomTitle(title);
        // 中间的信息以一个view的形式设置进去
        TextView msg = new TextView(this);
        msg.setText("自定义弹出提示信息");
        msg.setTextSize(24);
        msg.setGravity(Gravity.CENTER);
        msg.setPadding(20, 40, 20, 40);
        builder.setView(msg);

        builder.setPositiveButton("确认", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                System.out.println("确认执行函数");
            }
        }).setNegativeButton("取消", null);
        // 调用 show()方法后得到 dialog对象
        AlertDialog dialog = builder.show();
        final Button positiveButton = dialog.getButton(AlertDialog.BUTTON_POSITIVE);
        final Button negativeButton=dialog.getButton(AlertDialog.BUTTON_NEGATIVE);
        LinearLayout.LayoutParams positiveParams =(LinearLayout.LayoutParams)positiveButton.getLayoutParams();
        positiveParams.gravity = Gravity.CENTER;
        positiveParams.setMargins(10,10,10,10);
        positiveParams.width = 0;
        // 安卓下面有三个位置的按钮,默认权重为 1,设置成 500或更大才能让两个按钮看起来均分
        positiveParams.weight = 500;
        LinearLayout.LayoutParams negativeParams =(LinearLayout.LayoutParams)negativeButton.getLayoutParams();
        negativeParams.gravity = Gravity.CENTER;
        negativeParams.setMargins(10,10,10,10);
        negativeParams.width = 0;
        negativeParams.weight = 500;
        positiveButton.setLayoutParams(positiveParams);
        negativeButton.setLayoutParams(negativeParams);
        positiveButton.setBackgroundColor(Color.parseColor("#FF733E"));
        positiveButton.setTextColor(Color.parseColor("#FFFFFF"));
        negativeButton.setBackgroundColor(Color.parseColor("#DDDDDD"));
    }

 

你可能感兴趣的:(安卓—自定义 AlertDialog 的样式)