Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.5k views
in Technique[技术] by (71.8m points)

java - How to set round corners for a custom Dialog?

This is code for my custom Dialog:

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*/
    
    }
}

I followed instructions from other answers by first creating this drawable xml called dialog_bg:

<?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>

Then setting it as the background of the layout_dialog xml:

android:background="@drawable/dialog_bg"

But I can't do the final step which is to set the dialog's root view to transparent:

dialogBrightness.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));

because there's no getWindow() function.

Also when they say root view do they mean the one that I set to null in the inflate function above?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can use the MaterialAlertDialogBuilder included in the Material Components library:

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();

    }
}

with:

<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>

enter image description here


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...