Диалоговое окно настраиваемого предупреждения с использованием DialogFragment не работает должным образом - PullRequest
0 голосов
/ 26 мая 2020

Я пытаюсь реализовать собственный конструктор предупреждений, который должен отображать настраиваемый макет, который я хочу использовать. Я создал класс под названием «AlertDialogClass», который расширяет DialogFragment. Я пытаюсь показать этот класс построителя предупреждений из фрагмента.

Я не получаю никаких ошибок или ошибок sh при использовании этого класса AlertDialogClass, но тот макет, который должен быть показан, показывает только белый экран. Я много чего пробовал, но ничего не помогает. Я не могу понять, почему это происходит или что я делаю неправильно.

Вот мой файл макета.

<?xml version="1.0" encoding="utf-8"?>
<androidx.cardview.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="230dp"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    app:cardBackgroundColor="@color/backgroundElevation2dp"
    app:cardCornerRadius="14dp"
    app:cardElevation="8dp"
    >

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:padding="@dimen/padding18dp"
        android:gravity="center_horizontal"
        >

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical"
            android:layout_alignParentTop="true"
            android:gravity="center_horizontal"
            >
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Connection Not Available !!"
            android:textAppearance="@style/CardTextView"
            />

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Please Check Your Internet Connection And Try Again"
            android:textAppearance="@style/CardTextViewSmall"
            android:layout_margin="@dimen/margin3dp"
            />

        </LinearLayout>

        <ImageView
            android:layout_width="80dp"
            android:layout_height="80dp"
            android:src="@drawable/no_connection"
            android:layout_centerInParent="true"
            />

        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="@drawable/btn_background1"
            android:text="Try Again"
            android:textAppearance="@style/CardTextView"
            android:layout_marginLeft="@dimen/margin38dp"
            android:layout_marginRight="@dimen/margin38dp"
            android:textAlignment="center"
            android:layout_alignParentBottom="true"
            android:padding="@dimen/padding5dp"
            android:id="@+id/adTryAgain"
            />
    </RelativeLayout>

</androidx.cardview.widget.CardView>

Мой класс диалогового окна предупреждений.

public class AlertDialogClass extends DialogFragment implements View.OnClickListener {

    private TextView tryAgainButton ;
    private AlertDialogClickInterface clickInterface ;


    public AlertDialogClass(AlertDialogClickInterface clickInterface) {
        this.clickInterface = clickInterface;
    }

    @NonNull
    @Override
    public Dialog onCreateDialog(@Nullable Bundle savedInstanceState) {

        View layout = getActivity().getLayoutInflater().inflate(R.layout.alert_dialog,null);
        tryAgainButton = (TextView)layout.findViewById(R.id.adTryAgain);
        tryAgainButton.setOnClickListener(this);

        Dialog dialog = new Dialog(getActivity());
        dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        dialog.setContentView(layout);

        return dialog;

    }


    @Override
    public void onClick(View v) {

        if (v.getId() == R.id.adTryAgain){
            clickInterface.OnAlertButtonClicked();
        }

    }

    public interface AlertDialogClickInterface {
        void OnAlertButtonClicked();
    }

}

Фрагмент, из которого я хочу показать диалоговое окно с предупреждением.

try {

    if (CheckConnection.isConnected())
        getDataFromViewModel();

    else {

        AlertDialogClass dialogClass = new AlertDialogClass( this);
        dialogClass.show(getChildFragmentManager(),dialogClass.getTag());
    }
} catch (InterruptedException e) {
    e.printStackTrace();
} catch (IOException e) {
    e.printStackTrace();
}

Ожидаемый макет должен быть таким:

Layout I created for alert builder

Но фактический результат выглядит следующим образом:

original output

Вот стили, которые я использовал в текстовых представлениях

<style name="CardTextView" parent="TextAppearance.AppCompat.Widget.ActionBar.Subtitle" >
    <item name="android:textColor">@color/textColorWhite1</item>
    <item name="android:textStyle">bold</item>
    <item name="android:textSize">@dimen/textSize18</item>
    <item name="android:fontFamily">sans-serif-smallcaps</item>
</style>

<style name="CardTextViewSmall" parent="TextAppearance.AppCompat.Widget.ActionBar.Subtitle" >
    <item name="android:textColor">@color/textColorWhite2</item>
    <item name="android:textStyle">bold</item>
    <item name="android:textSize">@dimen/textSize14</item>
    <item name="android:fontFamily">sans-serif-smallcaps</item>
</style>

1 Ответ

1 голос
/ 27 мая 2020

Попробуйте изменить с:

        Dialog dialog = new Dialog(getActivity());
        dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        dialog.setContentView(layout);

На это:

    Dialog dialog = new Dialog(getActivity());
    dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
    dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
    dialog.getWindow().setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
    dialog.setContentView(layout);

Добавлено 1

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

этот используется для сохранения прозрачности фона вокруг вашего диалога.


dialog.getWindow().setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);

И этот сохраняет высоту вашего диалогового окна точно так же, как это было установлено в XML файл.

...