ConstraintLayout неправильное поведение - PullRequest
0 голосов
/ 17 января 2019

Это мой диалог,

public class TestDialog extends DialogFragment {

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        return inflater.inflate(R.layout.test_dialog, container, false);
    }
}

Когда я использую RelativeLayout для моего дизайна, как показано ниже,

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical">

    <TextView
        android:id="@+id/textTitle"
        android:layout_width="match_parent"
        android:layout_height="@dimen/dp48"
        android:layout_alignParentTop="true"
        android:fontFamily="@font/trebuchet"
        android:gravity="center"
        android:text="Test Dialog"
        android:textColor="?attr/colorAccent"
        android:textSize="18sp" />

    <ImageView
        android:id="@+id/icon"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/textTitle"
        android:src="@drawable/ic_baseline_public_24px"
        android:tint="@color/black" />

    <TextView
        android:id="@+id/text"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/textTitle"
        android:layout_marginStart="5dp"
        android:layout_toEndOf="@+id/icon"
        android:fontFamily="@font/trebuchet"
        android:text="This is very long text, This is very long text, This is very long text" />

    <com.google.android.material.button.MaterialButton
        android:id="@+id/imageView_close"
        style="@style/Widget.MaterialComponents.Button.OutlinedButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/text"
        android:layout_centerHorizontal="true"
        android:contentDescription="@string/close"
        android:src="@drawable/ic_baseline_close_24dx"
        android:text="@string/cancel" />
</RelativeLayout>

Я получаю этот вывод.

enter image description here

Но когда я использую ConstraintLayout для своего дизайна, как показано ниже,

<?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"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical">

    <TextView
        android:id="@+id/textTitle"
        android:layout_width="0dp"
        android:layout_height="@dimen/dp48"
        android:fontFamily="@font/trebuchet"
        android:gravity="center"
        android:text="Test Dialog"
        android:textColor="?attr/colorAccent"
        android:textSize="18sp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <ImageView
        android:id="@+id/icon"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/textTitle"
        android:src="@drawable/ic_baseline_public_24px"
        android:tint="@color/black"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/textTitle" />

    <TextView
        android:id="@+id/text"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginStart="5dp"
        android:fontFamily="@font/trebuchet"
        android:text="This is very long text, This is very long text, This is very long text"
        app:layout_constraintStart_toEndOf="@+id/icon"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/textTitle" />

    <com.google.android.material.button.MaterialButton
        android:id="@+id/imageView_close"
        style="@style/Widget.MaterialComponents.Button.OutlinedButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:contentDescription="@string/close"
        android:src="@drawable/ic_baseline_close_24dx"
        android:text="@string/cancel"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/text" />
</androidx.constraintlayout.widget.ConstraintLayout>

Я получаю следующий вывод.

enter image description here

Я не знаю, почему это странное поведение. Только в диалоге я получаю это поведение.

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

Ответы [ 3 ]

0 голосов
/ 17 января 2019

все, что вам нужно сделать, это установить тему в вашем диалоге.

 @Override
    public int getTheme() {
        return R.style.dialog;
    }

стиль

<style name="dialog" parent="android:Theme.Dialog">
        <item name="android:windowBackground">@drawable/radius</item>
        <item name="android:windowMinWidthMajor">80%</item>
        <item name="android:windowMinWidthMinor">85%</item>
        <item name="android:windowNoTitle">true</item>
    </style>

radius.xml

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
    <solid android:color="@color/white" />
    <corners android:radius="10dp" />
    <padding
        android:bottom="8dp"
        android:left="8dp"
        android:right="8dp"
        android:top="8dp" />
</shape>
0 голосов
/ 17 января 2019

Во-первых, это не ConstraintLayout, а способ реализации самого Dialog. Это предложение и согласно Диалоговая документация :

Класс Dialog является базовым классом для диалогов, но вам следует избегать создание экземпляра диалога напрямую. Вместо этого используйте один из следующих подклассы:

AlertDialog
Диалог, который может показать заголовок, до трех кнопок, список выбираемых элементов или пользовательский макет.

DatePickerDialog or TimePickerDialog
Диалог с предопределенным пользовательским интерфейсом, который позволяет пользователю выбрать дату или время.

Так что в основном вы будете использовать setView api:

@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
    AlertDialog.Builder builder = new AlertDialog.Builder(requireActivity());
    // Setting my layout here
    builder.setView(R.layout.my_layout);
    builder.setPositiveButton(/* My Methods */)
           .setNegativeButton(/* My Methods */);
    return builder.create();
}

Прочтите об этом в Создание документации пользовательского макета . Если вы хотите больше настроек, создайте собственную тему в values> styles.xml, которую можно использовать во всем приложении, или просто установив ее вместе со сборщиком, например:

new AlertDialog.Builder(requireActivity(), R.style.My_Alert_Dialog_Theme);
0 голосов
/ 17 января 2019

Я думаю, что проблема в android:layout_width="match_parent" в вашем теге ConstraintLayout. Поскольку диалог не имеет фиксированной ширины, использование match_parent не будет работать. Может быть, вы могли бы установить фиксированную ширину или минимальную ширину.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...