安卓—自定义 AlertDialog 的样式
效果图
1.在style.xml下添加
<!-- 自定义弹出样式 --> <style name="MyDialogStyle" parent="Theme.AppCompat.Light.Dialog.Alert"> <!--是否浮在窗口之上--> <!--<item name="android:windowIsFloating">true</item>--> <!--半透明--> <!--<item name="android:windowIsTranslucent">true</item>--> <!--是否显示title--> <item name="android:windowNoTitle">true</item> <!--dialog之外没有焦点的区域是否罩上黑色半透明--> <item name="android:background">@color/white</item> <item name="android:textColor">@color/gray</item> <item name="android:textSize">@dimen/f24</item> <!-- 这里是修改顶部标题背景颜色,具体颜色自己定,可以是图片 --> <item name="android:topDark">@color/blue_alert</item> <!-- 这里是修改内容区域背景颜色 --> <item name="android:layout_gravity">center</item> <item name="buttonBarButtonStyle">@color/white</item> </style>
2.在主体配置里引入自定义的AlertDialog主题
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")); }
作者:[一柒微笑]