Ограничение выравнивания текста по центру кнопки компоновки

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

введите здесь описание изображения

Как вы можете видеть на изображении, я устанавливаю ширину на 0dp (любой размер), но текст не прилипает к центру, что обычно является нормальным для текста кнопки.

Я пробовал: - установить гравитацию по центру - установить textAlignment по центру

Похоже, что эти свойства не могут работать с шириной 0dp (любой размер).

Поэтому я попытался установить ширину match_parent, используя центр тяжести.

введите здесь описание изображения

Это немного правее.

Кто-нибудь знает, как исправить такое поведение?

Обратите внимание, что я использую alpha4

compile 'com.android.support.constraint:constraint-layout:1.0.0-alpha4'

XML-код

<android.support.constraint.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:id="@+id/content_login"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    tools:context="br.com.marmotex.ui.LoginActivityFragment"
    tools:showIn="@layout/activity_login">

    <Button
        android:text="Log in"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:id="@+id/btLogin"
        android:layout_marginTop="48dp"
        app:layout_constraintTop_toBottomOf="@+id/textView6"
        android:layout_marginEnd="16dp"
        app:layout_constraintRight_toRightOf="@+id/content_login"
        android:layout_marginRight="16dp"
        android:layout_marginStart="16dp"
        app:layout_constraintLeft_toLeftOf="@+id/content_login"
        android:layout_marginLeft="16dp"
        android:textColor="@android:color/white"
        android:background="@color/BackgroundColor" />

</android.support.constraint.ConstraintLayout>

EDIT Это была ошибка в ConstraintLayout alpha4.

ОБНОВЛЕНИЕ Компания Google выпустила alpha5, приведенный выше код теперь работает. Примечание к выпуску


person Clayton Oliveira    schedule 03.08.2016    source источник


Ответы (5)


Это немного правее.

Я думаю, что маржа (ы) вызывает это. И, по моему опыту, это влияет не только на кнопки. Margin тоже портит TextInputEditText.

Ниже приведен рабочий код, но обратите внимание на android:layout_width="match_parent" на кнопке. Каждый раз, когда я щелкал в редакторе, он менялся на android:layout_width="0dp" и нарушал выравнивание кнопки.

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.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:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">


    <Button
        android:id="@+id/button_survey"
        android:layout_width="match_parent" 
        android:layout_height="52dp"
        android:text="Button"
        app:layout_constraintBottom_toBottomOf="@+id/activity_main"
        app:layout_constraintLeft_toLeftOf="@+id/activity_main"
        app:layout_constraintRight_toRightOf="@+id/activity_main"
        app:layout_constraintTop_toTopOf="@+id/activity_main"
        tools:text="@string/main_activity_btn_survey"
        android:layout_marginEnd="8dp"
        android:layout_marginRight="8dp"
        android:layout_marginStart="8dp"
        android:layout_marginLeft="8dp" />


</android.support.constraint.ConstraintLayout>

Вдохновленный решением Hobo joe, ниже показано, как я предпочитаю это делать. Его решение работает, но все же нужно использовать отступы для создания интервалов. Если вместо этого использовалось поле, выравнивание текста кнопки будет немного вправо. Поэтому я использовал отступы в LinearLayout (или ConstraintLayout) вместо поля на кнопке.

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <LinearLayout
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:layout_constraintLeft_toLeftOf="@+id/activity_main"
        app:layout_constraintTop_toTopOf="@+id/activity_main"
        app:layout_constraintRight_toRightOf="@+id/activity_main"
        app:layout_constraintBottom_toBottomOf="@+id/activity_main"
        android:padding="16dp">
        <Button
            android:text="Button"
            android:layout_width="match_parent"
            android:layout_height="52dp"
            android:id="@+id/button_survey"
            android:layout_weight="1"
            tools:text="@string/main_activity_btn_survey"
            />
    </LinearLayout>
</android.support.constraint.ConstraintLayout>
person Marchell Imanuel    schedule 04.08.2016
comment
Google выпустил alpha5, обновите его, и вам больше не понадобится этот обходной путь. - person Clayton Oliveira; 07.08.2016

Ты пытался ?

android:textAlignment="center"

Это работает для меня.

person SoH    schedule 29.04.2017

Это ошибка. Однако вы можете обойти это, поместив кнопку внутри LinearLayout (или другой стандартной ViewGroup). Установите родительское представление и ширину кнопки на match_parent и переместите все ограничения, которые у вас были на кнопке, в родительский макет.

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    app:layout_constraintLeft_toLeftOf="@+id/parent_left"
    app:layout_constraintTop_toTopOf="@+id/parent_top"
    app:layout_constraintRight_toRightOf="@+id/parent_right">

    <Button
        android:id="@+id/test"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Centered Text"/>

</LinearLayout>
person Hobo Joe    schedule 03.08.2016
comment
Можете ли вы опубликовать свой код макета? Я только что проверил с опубликованным XML, и это сработало. - person Hobo Joe; 03.08.2016

Ну, я думаю, это из-за этих ограничений app:layout_constraintRight_toRightOf app:layout_constraintLeft_toLeftOf

замените текущую кнопку на эту:

    <Button
    android:text="Log in"
    android:layout_width="match_parent"
    android:layout_height="48dp"
    android:id="@+id/btLogin"
    android:textColor="@android:color/white"
    android:background="@color/BackgroundColor"
    android:gravity="center"
    android:textAlignment="center"
    android:layout_marginTop="100dp"
    tools:layout_editor_absoluteX="-1dp"
    app:layout_constraintTop_toBottomOf="@+id/textView6" />

Надеюсь, это поможет.

person M___K    schedule 05.08.2016

Кажется, проблема связана с android:layout_width="match_parent" при использовании внутри ConstraintLayout. Просто установите android:layout_width="0dp" и добавьте ограничения app:layout_constraintStart_toStartOf="parent" и app:layout_constraintEnd_toEndOf="parent", все будет нормально.

<Button
     android:layout_width="0dp"
     android:layout_height="wrap_content"
     android:text="Continue"
     app:layout_constraintEnd_toEndOf="parent"
     app:layout_constraintStart_toStartOf="parent" />
person Chandra Pratap Singh    schedule 11.06.2020