Java 如何为自定义对话框设置圆角?
这是我的自定义对话框的代码:Java 如何为自定义对话框设置圆角?,java,android,android-alertdialog,android-dialogfragment,material-components-android,Java,Android,Android Alertdialog,Android Dialogfragment,Material Components Android,这是我的自定义对话框的代码: public class DialogBrightness extends AppCompatDialogFragment { @NonNull @Override public Dialog onCreateDialog(@Nullable Bundle savedInstanceState) { LayoutInflater inflater = getActivity().getLayoutInflater(); View view = i
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>
但我无法完成最后一步,即将对话框的根视图设置为透明:
dialogBrightness.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
因为没有getWindow()函数
此外,当他们说根视图时,他们是指我在上面的充气功能中设置为null的视图吗?您可以使用材料组件库中包含的
MaterialAlertDialogBuilder
:
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/ShapeAppearanceOverlay.MyApp.Dialog.Rounded
圆的
8dp
我强烈推荐@GabrieleMariotti的答案,但我在这里写这篇文章是想看看你是如何以你原来的方式实现的 没有getWindow()函数 您可以使用
requireView()
作为:
dialogBrightness.requireView().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
另外,当他们说根视图时,他们是指我在上面的充气函数中设置为null的视图吗
是的。通常,不建议将null
作为root
参数传递,因为需要root
视图来计算当前由LayoutInflater
膨胀的视图的布局参数。相反,您应该这样使用它:
View view = LayoutInflater.from(requireContext()).inflate(R.layout.layout_dialog, rootView, false);
这里,第三个参数是attachToRoot
,它作为false
传递,这一个更简单。rootView到底是什么?rootView
是类型为ViewGroup
的对象(它扩展了View
类,是布局和视图容器的基类)。如果attachToRoot为false,rootView
仅用于计算布局参数,否则当前膨胀的view
将是rootView
的子级。
dialogBrightness.requireView().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
View view = LayoutInflater.from(requireContext()).inflate(R.layout.layout_dialog, rootView, false);