问题
平时使用AlertDialog弹框限制比较多,如果使用Google原生设计风格使用比价方便,但是如果需要根据UI定制开发,则受到很多限制,一般我们需要自定义布局。
结合DialogFragment使用
AlertDialogFragment
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(getActivity());
AlertDialog alertDialog = dialogBuilder.create();
View uninstallView = LayoutInflater.from(getActivity()).inflate(R.layout.my_dialog, null);
// 设置自定义布局
alertDialog.setView(uninstallView);
// 将弹框边距,水平铺满
Window dialogWindow = alertDialog.getWindow();
// 把 DecorView 的默认 padding 取消,同时 DecorView 的默认大小也会取消
dialogWindow.getDecorView().setPadding(0, 0, 0, 0);
// 设置宽度
WindowManager.LayoutParams lp = dialogWindow.getAttributes();
lp.width = ViewGroup.LayoutParams.MATCH_PARENT;
lp.height = ViewGroup.LayoutParams.WRAP_CONTENT;
// 将弹框背景去掉采用布局自己背景
dialogWindow.getDecorView().setBackgroundColor(Color.TRANSPARENT);
// 设置弹框的位置 Gravity.BOTTOM Gravity.TOP Gravity.CENTER
dialogWindow.setGravity(Gravity.BOTTOM);
return alertDialog;
}
//调用AlertDialogFragment弹框
showDialogFragment(new AlertDialogFragment(),0,0);
private void showDialogFragment(@NonNull DialogFragment fragment,
@StringRes int title, @StringRes int text) {
FragmentTransaction ft = getFragmentManager().beginTransaction();
Fragment prev = getFragmentManager().findFragmentByTag("dialog");
if (prev != null) {
ft.remove(prev);
}
Bundle args = new Bundle();
if (title != 0) {
args.putInt(TITLE, title);
}
args.putInt(TEXT, text);
fragment.setArguments(args);
fragment.show(ft, "dialog");
}
my_dialog样式
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<LinearLayout
android:id="@+id/son_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginHorizontal="12dp"
android:background="@color/white"
android:layout_marginBottom="20dp"
android:orientation="vertical">
//自定义自己的布局
</LinearLayout>
</LinearLayout>
</LinearLayout>
重点
android:layout_marginHorizontal="12dp"
android:layout_marginBottom="20dp"
设置my_dialog布局中的son_view字布局的边距控制上下左右边距。
效果
先设置弹框大体位置,在设置边距进行调整,Gravity.BOTTOM Gravity.TOP Gravity.CENTER。
![](https://img.haomeiwen.com/i7717043/85227f1658a7eba9.png)
网友评论