How to set the size of a DialogFragment in Android

183 Views Asked by At

I have a DialogFragment and I would like to set the size of it to 80% of the whole screen. For that I use the following code:

public class DialogFR_LevelEnd_Test extends DialogFragment {


    public DialoagFragmentLevelEndingBinding binding;


    public static DialogFR_LevelEnd_Test newInstance(double co2SavingsScore, double neededCO2SavingScore, int currentLevel) {
        DialogFR_LevelEnd_Test fragment = new DialogFR_LevelEnd_Test();
        Bundle args = new Bundle();
        fragment.setArguments(args);

        return fragment;
    }

    public void onViewCreated(Bundle savedInstanceState) {

        //Attempt 1
        DisplayMetrics displayMetrics = new DisplayMetrics();
        getActivity().getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);

        int screenWidth = (int) (displayMetrics.widthPixels * 0.80);
        int screenHeight = (int) (displayMetrics.heightPixels * 0.80);

        WindowManager.LayoutParams params = getDialog().getWindow().getAttributes();
        params.width = screenWidth;
        params.height = screenHeight;
        getDialog().getWindow().setAttributes(params);
    }

    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        binding = DialoagFragmentLevelEndingBinding.inflate(inflater, container, false);

        //Attempt 2
        DisplayMetrics displayMetrics = new DisplayMetrics();
        getActivity().getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);

        int screenWidth = (int) (displayMetrics.widthPixels * 0.80);
        int screenHeight = (int) (displayMetrics.heightPixels * 0.80);

        WindowManager.LayoutParams params = getDialog().getWindow().getAttributes();
        params.width = screenWidth;
        params.height = screenHeight;
        getDialog().getWindow().setAttributes(params);


        return binding.getRoot();

    }



    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

    }


}

So I try 2 attempst but none of them works. No matter what number I choose, the size is always the same.

Here is the XML layout file of the DialogFragment:

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    >



    <androidx.constraintlayout.widget.ConstraintLayout
        android:id="@+id/right_outer_constraintLayout"
        android:layout_width="0dp"
        android:layout_height="0dp"
        app:layout_constraintWidth_percent="0.44"
        app:layout_constraintHeight_percent="0.65"
        android:orientation="vertical"
        android:background="@drawable/rim"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.98"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        android:padding="10dp"
        app:layout_constraintVertical_bias="0.9">


        <androidx.constraintlayout.widget.ConstraintLayout
            android:id="@+id/rigthInnerConstraintLayout"
            android:layout_width="0dp"
            android:layout_height="0dp"
            android:background="@color/white"
            app:layout_constraintBottom_toBottomOf="@+id/right_outer_constraintLayout"
            app:layout_constraintEnd_toEndOf="@+id/right_outer_constraintLayout"
            app:layout_constraintHorizontal_bias="1.0"
            app:layout_constraintStart_toStartOf="@+id/right_outer_constraintLayout"

            app:layout_constraintTop_toTopOf="@+id/right_outer_constraintLayout"
            app:layout_constraintVertical_bias="1.0">


            <LinearLayout
                android:id ="@+id/linearLayoutForButtons"
                android:layout_width="0dp"
                android:layout_height="30dp"
                android:orientation="horizontal"
                app:layout_constraintTop_toTopOf="parent"
                app:layout_constraintEnd_toEndOf="parent"
                app:layout_constraintStart_toStartOf="parent"
                >


                <ToggleButton
                    android:id="@+id/tbutton_highScore_lastWeek"
                    android:layout_width="wrap_content"
                    android:layout_height="match_parent"
                    android:layout_weight="1"
                    android:background="@drawable/tbutton_selector"
                    android:textAllCaps="false"
                    android:textOff="@string/last_week"
                    android:textOn="@string/last_week"
                    android:textSize="10sp"
                    app:layout_constraintTop_toTopOf="parent"
                    tools:ignore="TouchTargetSizeCheck" />

                <View
                    android:id="@+id/line1"
                    android:layout_width="3dp"
                    android:layout_height="match_parent"
                    android:background="#bcbcbc" />

                <ToggleButton
                    android:id="@+id/tbutton_highScore_lastMonth"
                    android:layout_width="wrap_content"
                    android:layout_height="match_parent"
                    android:layout_weight="1"
                    android:background="@drawable/tbutton_selector"
                    android:textAllCaps="false"
                    android:textOff="@string/last_month"
                    android:textOn="@string/last_month"
                    android:textSize="10sp"
                    tools:ignore="TouchTargetSizeCheck" />

                <View
                    android:id="@+id/line2"
                    android:layout_width="3dp"
                    android:layout_height="match_parent"

                    android:background="#bcbcbc" />

                <ToggleButton
                    android:id="@+id/tbutton_highScore_overall"
                    android:layout_width="wrap_content"
                    android:layout_height="match_parent"
                    android:layout_weight="1"
                    android:background="@drawable/tbutton_selector"
                    android:textAllCaps="false"
                    android:textOff="@string/overall"
                    android:textOn="@string/overall"
                    android:textSize="10sp"
                    tools:ignore="TouchTargetSizeCheck" />
            </LinearLayout>

            <androidx.recyclerview.widget.RecyclerView
                android:id="@+id/rv_highScoreStatisticsToBeDisplayed"
                android:layout_width="0dp"
                android:layout_height="0dp"
                android:layout_marginLeft="4dp"
                android:layout_marginTop="4dp"
                android:layout_marginRight="4dp"
                app:layout_constraintBottom_toBottomOf="parent"
                app:layout_constraintEnd_toEndOf="parent"
                app:layout_constraintStart_toStartOf="parent"
                app:layout_constraintTop_toBottomOf="@id/linearLayoutForButtons" />




        </androidx.constraintlayout.widget.ConstraintLayout>
    </androidx.constraintlayout.widget.ConstraintLayout>





    <TextView
        android:id="@+id/textView_LevelFinished"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Level Finished"
        android:textSize="45sp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.50"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.05" />

    <ImageView
        android:id="@+id/imageView_CloseSymbol"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:layout_constraintBottom_toBottomOf="@+id/textView_LevelFinished"


        app:layout_constraintStart_toEndOf="@+id/textView_LevelFinished"
        app:layout_constraintTop_toTopOf="@+id/textView_LevelFinished"
        app:layout_constraintVertical_bias="0.512"
        app:srcCompat="@drawable/ic_close_symbol_foreground" />

    <ImageView
        android:id="@+id/imageView_Checkmark"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:layout_constraintBottom_toBottomOf="@+id/textView_LevelFinished"

        app:layout_constraintStart_toEndOf="@+id/textView_LevelFinished"
        app:layout_constraintTop_toTopOf="@+id/textView_LevelFinished"
        app:srcCompat="@drawable/ic_check_mark_foreground" />

    <TextView
        android:id="@+id/textView_LevelFinishedMessageCO2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="12dp"
        android:text="You needed to save x g of CO2 and you got y g"
        android:textSize="14sp"
        app:layout_constraintHorizontal_bias="0.02"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/imageView_CloseSymbol" />

    <TextView
        android:id="@+id/textView_LevelFinishedMessageGas"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="25dp"
        android:text="You saved 10 kWh of Gas"
        android:textSize="14sp"
        app:layout_constraintEnd_toEndOf="@+id/textView_LevelFinishedMessageCO2"
        app:layout_constraintHorizontal_bias="0.4"
        app:layout_constraintStart_toStartOf="@+id/textView_LevelFinishedMessageCO2"
        app:layout_constraintTop_toBottomOf="@+id/textView_LevelFinishedMessageCO2" />

    <ImageView
        android:id="@+id/imageViewGasSymbol"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="15dp"
        app:layout_constraintBottom_toBottomOf="@+id/textView_LevelFinishedMessageGas"
        app:layout_constraintStart_toEndOf="@+id/textView_LevelFinishedMessageGas"
        app:layout_constraintTop_toTopOf="@+id/textView_LevelFinishedMessageGas"
        app:srcCompat="@drawable/gas2" />

    <ImageView
        android:id="@+id/imageView_NextLevelSymbol"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:layout_constraintBottom_toTopOf="@+id/textView_RepeatLevel"
        app:layout_constraintEnd_toEndOf="@+id/textView_LevelFinishedMessageCO2"
        app:layout_constraintHorizontal_bias="0.85"
        app:layout_constraintStart_toStartOf="@+id/textView_LevelFinishedMessageCO2"
        app:layout_constraintTop_toTopOf="@+id/imageView_RepeatSymbol"
        app:srcCompat="@drawable/ic_arrow_forward_foreground" />

    <ImageView
        android:id="@+id/imageView_RepeatSymbol"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:layout_constraintEnd_toEndOf="@+id/textView_LevelFinishedMessageCO2"
        app:layout_constraintHorizontal_bias="0.35"
        app:layout_constraintStart_toStartOf="@+id/textView_LevelFinishedMessageCO2"
        app:layout_constraintTop_toBottomOf="@+id/textView_HighscoreMessagePositions"
        app:srcCompat="@drawable/ic_repeat_symbol_foreground" />

    <TextView
        android:id="@+id/textView_RepeatLevel"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/repeat_level"
        android:textStyle="bold"
        android:textSize="15sp"
        app:layout_constraintEnd_toEndOf="@+id/imageView_RepeatSymbol"
        app:layout_constraintStart_toStartOf="@+id/imageView_RepeatSymbol"
        app:layout_constraintTop_toBottomOf="@+id/imageView_RepeatSymbol" />

    <TextView
        android:id="@+id/textView_NextLevel"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/next_level"
        android:textStyle="bold"
        android:textSize="15sp"
        app:layout_constraintEnd_toEndOf="@+id/imageView_NextLevelSymbol"
        app:layout_constraintStart_toStartOf="@+id/imageView_NextLevelSymbol"
        app:layout_constraintTop_toBottomOf="@+id/imageView_NextLevelSymbol" />

    <ImageView
        android:id="@+id/imageView_leaf"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="12dp"
        app:layout_constraintBottom_toBottomOf="@+id/textView_LevelFinishedMessageCO2"
        app:layout_constraintStart_toEndOf="@+id/textView_LevelFinishedMessageCO2"
        app:layout_constraintTop_toTopOf="@+id/textView_LevelFinishedMessageCO2"
        app:srcCompat="@drawable/leaf" />

    <TextView
        android:id="@+id/textView_TopScores"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Top Scores for this Level"
        android:textSize="21sp"
        android:layout_marginBottom="4dp"
        app:layout_constraintBottom_toTopOf="@+id/right_outer_constraintLayout"
        app:layout_constraintEnd_toEndOf="@+id/right_outer_constraintLayout"
        app:layout_constraintStart_toStartOf="@+id/right_outer_constraintLayout" />

    <TextView
        android:id="@+id/textView_HighscoreMessage"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="25dp"
        android:text="You made it to the Top Score list"
        android:textSize="14sp"
        app:layout_constraintEnd_toEndOf="@+id/textView_LevelFinishedMessageCO2"
        app:layout_constraintStart_toStartOf="@+id/textView_LevelFinishedMessageCO2"
        app:layout_constraintTop_toBottomOf="@+id/textView_LevelFinishedMessageGas" />

    <TextView
        android:id="@+id/textView_HighscoreMessagePositions"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="1st this week, 3rd this month, 6th overall"
        android:textSize="14sp"
        android:layout_marginTop="20dp"
        app:layout_constraintEnd_toEndOf="@+id/textView_HighscoreMessage"
        app:layout_constraintStart_toStartOf="@+id/textView_HighscoreMessage"
        app:layout_constraintTop_toBottomOf="@+id/textView_HighscoreMessage" />
</androidx.constraintlayout.widget.ConstraintLayout>

Do you know how to do this? Either in the XML layout file or in the Java file?

Update: Here is my themes.xml file

<resources xmlns:tools="http://schemas.android.com/tools">
    <!-- Base application theme. -->
    <style name="Theme.Game" parent="Theme.MaterialComponents.DayNight.DarkActionBar">
        <!-- Primary brand color. -->
        <item name="colorPrimary">@color/purple_500</item>
        <item name="colorPrimaryVariant">@color/purple_700</item>
        <item name="colorOnPrimary">@color/white</item>
        <!-- Secondary brand color. -->
        <item name="colorSecondary">@color/teal_200</item>
        <item name="colorSecondaryVariant">@color/teal_700</item>
        <item name="colorOnSecondary">@color/black</item>
        <!-- Status bar color. -->
        <item name="android:statusBarColor" tools:targetApi="l">?attr/colorPrimaryVariant</item>
        <!-- Customize your theme here. -->
    </style>




    <style name="SCBSwitch" parent="Theme.AppCompat.Light">
        <!-- active thumb & track color (30% transparency) -->
        <item name="colorControlActivated">#cd0000</item>

        <!-- inactive thumb color -->
        <item name="colorSwitchThumbNormal">#327bff
        </item>

        <!-- inactive track color (30% transparency) -->
        <item name="android:colorForeground">#327bff
        </item>


    </style>

    <style name="SwitchStyle">
        <item name="colorSwitchThumbNormal">#cd0000</item>
        <item name="colorControlActivated">#327bff</item>
        <item name="android:colorForeground">@color/black </item>
    </style>

    <style name="CustomAlertDialogTheme" parent="ThemeOverlay.Material3.Dialog.Alert">
        <item name="windowFixedWidthMajor">20%</item><!--for landscape-->
        <item name="windowFixedWidthMinor">20%</item><!--for portrait-->
        <item name="alertDialogTheme">@style/CustomAlertDialogTheme</item>
    </style>

    

</resources>

Update: I tried the solution posted in the answer below but unfortunately, I does not work. Thus, I still have not solved this issue and I would like to know if someone of you has any suggestion as to how to do this?

2

There are 2 best solutions below

1
ltp On BEST ANSWER
public class DialogFR_LevelEnd_Test extends DialogFragment {

    public DialogFragmentLevelEndingBinding binding;

    public static DialogFR_LevelEnd_Test newInstance(double co2SavingsScore, double neededCO2SavingScore, int currentLevel) {
        DialogFR_LevelEnd_Test fragment = new DialogFR_LevelEnd_Test();
        Bundle args = new Bundle();
        fragment.setArguments(args);

        return fragment;
    }


    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        binding = DialogFragmentLevelEndingBinding.inflate(inflater, container, false);
        return binding.getRoot();

    }


    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        //The following sets the dialog size
        getDialog().setOnShowListener(
                dialog -> {   
                    Point availableDisplaySize = getAvailableDisplaySize(requireActivity());
                    int targetWidth = (int) (availableDisplaySize.x * .8f);
                    int targetHeight = (int) (availableDisplaySize.y * .8f);
                    WindowManager.LayoutParams params = getDialog().getWindow().getAttributes();
                    params.width = targetWidth;
                    params.height = targetHeight;
                    getDialog().getWindow().setAttributes(params);
                }
        );
    }
}
public class Util {
    static Point getAvailableDisplaySize(Context context) {
        if (context instanceof Activity && Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
            WindowMetrics metrics = ((Activity) context).getWindowManager().getCurrentWindowMetrics();
            WindowInsets windowInsets = metrics.getWindowInsets();
            Insets insets = windowInsets.getInsetsIgnoringVisibility(
                    WindowInsets.Type.navigationBars()
                            | WindowInsets.Type.displayCutout()
            );
            int width = metrics.getBounds().width() - insets.right + insets.left;
            int height = metrics.getBounds().height() - insets.top + insets.bottom;
            return new Point(width, height);
        } else {
            Display display = ((WindowManager) context.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
            Point size = new Point();
            display.getSize(size);
            return size;
        }
    }
}
2
Samuel Jarosiński On

You can set the width of all Dialogs by overriding the dialogTheme attribute in your theme with your own ThemeOverlay. That ThemeOverlay can then set android:windowMinWidthMajor and android:windowMinWidthMinor with the desired width in percentages.

Also, make sure that your Dialog class extends AppCompatDialogFragment, not DialogFragment. Otherwise, the solution won't work. You can remove the additional code from your Dialog class.

Here is the solution:

<style name="Theme.Game" parent="Theme.MaterialComponents.DayNight.DarkActionBar">
   ...
    <item name="dialogTheme">@style/CustomDialogTheme</item>
</style>

<style name="CustomDialogTheme" parent="@style/ThemeOverlay.AppCompat.Dialog">
    <item name="android:windowMinWidthMajor">80%</item>
    <item name="android:windowMinWidthMinor">80%</item>
</style>