java - 如何为自定义对话框设置圆角?
问题描述
这是我的自定义对话框的代码:
public class DialogBrightness extends AppCompatDialogFragment {
@NonNull
@Override
public Dialog onCreateDialog(@Nullable Bundle savedInstanceState) {
LayoutInflater inflater = getActivity().getLayoutInflater();
View view = inflater.inflate(R.layout.layout_dialog, null);
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
/*Build and create the dialog here*/
}
}
我按照其他答案的说明首先创建了这个名为 dialog_bg 的可绘制 xml:
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<solid
android:color="#fff5ee"/>
<corners
android:radius="30dp" />
<padding
android:left="10dp"
android:top="10dp"
android:right="10dp"
android:bottom="10dp" />
</shape>
然后将其设置为layout_dialog xml的背景:
android:background="@drawable/dialog_bg"
但我不能做最后一步,即将对话框的根视图设置为透明:
dialogBrightness.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
因为没有 getWindow() 函数。
此外,当他们说根视图时,他们的意思是我在上面的 inflate 函数中设置为 null 的那个吗?
解决方案
您可以使用MaterialAlertDialogBuilder
Material Components 库中包含的:
import androidx.fragment.app.DialogFragment;
public class CustomDialog extends DialogFragment {
//...
@NonNull
@Override
public Dialog onCreateDialog(@Nullable Bundle savedInstanceState) {
return new MaterialAlertDialogBuilder(getActivity(),R.style.MaterialAlertDialog_rounded)
.setTitle("Title")
.setMessage("Message")
.setPositiveButton("OK", null)
.create();
}
}
和:
<style name="MaterialAlertDialog_rounded" parent="@style/ThemeOverlay.MaterialComponents.MaterialAlertDialog">
<item name="shapeAppearanceOverlay">@style/ShapeAppearanceOverlay.MyApp.Dialog.Rounded</item>
</style>
<style name="ShapeAppearanceOverlay.MyApp.Dialog.Rounded" parent="">
<item name="cornerFamily">rounded</item>
<item name="cornerSize">8dp</item>
</style>
推荐阅读
- c# - How to create installation logs at a particular location using Wix toolset?
- java - Lucene 无法添加具有相同 FieldType 的多个字段
- java - Java 内存泄漏:为什么不收集无法访问的对象?
- javascript - 使用 django/javascript 时如何避免这个 Unexpected token 错误?
- sql-server-2008-r2 - 如何在 SQLCLR 2 中启用 TLS 1.2 支持?
- docker - Nginx 容器 502 Bad Gateway
- php - 如何在另一个数组中分配一个数组
- docker - Stackdriver Monitoring 代理配置,用于使用基于 docker 的容器进行 GCP 托管部署
- firebase - 图像保存到 Firebase 存储后,StreamProvider 返回 null 太快
- python - 用python下载二进制文件