Как выровнять TextView по его длине - PullRequest
0 голосов
/ 29 января 2020

У меня есть интерфейс с двумя ImageButtons и TextView среди них. TextView содержит число, и две ImageButtons управляют этим числом, добавляя или удаляя 1. Проблема заключается в том, что номер становится двумя цифрами: ширина TextView увеличивается и одна из двух кнопок ImageButtons перемещается.

One digit number Two digit number

Как вы можете видеть, когда число равно одному ди git, нет никаких проблем, но когда оно становится двухзначным, перемещается ImageButton со своего места. Я уже пробовал с android:layout_gravity и с android:gravity, но они не работают. Есть способ сохранить TextView "по центру" и убедиться, что ImageButton не перемещается?

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:autofit="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:paddingStart="5dp">

    <LinearLayout
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="1"
        android:gravity="center_vertical"
        android:orientation="vertical">

        <TextView
            android:id="@+id/foodName"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_marginEnd="10dp"
            android:gravity="center_vertical"
            android:hint="food_name"
            android:maxLines="2"
            android:textAllCaps="false"
            android:textColor="@android:color/black"
            android:textSize="18sp"
            android:textStyle="bold" />
    </LinearLayout>

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="end"
        android:gravity="end"
        android:orientation="horizontal"
        android:padding="5dp">

        <ImageButton
            android:id="@+id/addFood"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:background="@null"
            app:srcCompat="@drawable/ic_add_black_40dp" />

        <TextView
            android:id="@+id/foodQuantity"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center|center_horizontal"
            android:layout_marginStart="10dp"
            android:layout_marginEnd="10dp"
            android:gravity="center|center_horizontal"
            android:maxLength="2"
            android:text="0"
            android:textColor="#707070"
            android:textSize="20sp"
            android:textStyle="bold" />

        <ImageButton
            android:id="@+id/removeFood"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:background="@null"
            app:srcCompat="@drawable/ic_remove_black_40dp" />

    </LinearLayout>

</LinearLayout>

Это мой код и это макет члена RecyclerView, потому что я создал персонализированный элемент , Большое спасибо.

Ответы [ 3 ]

1 голос
/ 29 января 2020

Поскольку у вас wrap_content в вашем foodQuantity TextView, addFood будет перемещаться, чтобы учесть дополнительный интервал, необходимый для добавления нескольких цифр. Если вы хотите, чтобы положение кнопки фиксировалось, и чтобы кнопки не двигались, то вам придется придать вашей TextView фиксированную ширину, чтобы соответствовать максимальному количеству символов, которое вы можете ожидать.

1 голос
/ 29 января 2020

Я бы предложил вам использовать android:layout_weight, чтобы вы могли определить, какой элемент заполняет оставшееся пространство при необходимости. Таким образом, устанавливая TextView layout_weight, равный 1, и ImageButtons, layout_weight, равный 0, вы можете впоследствии установить android:gravity TextView, который определяет гравитацию внутри TextView, равным center, и он всегда будет центрирован.

НО : необходимо установить ширину LinearLayout на match_parent, чтобы она заполняла родительский элемент. Без этого LinearLayout никогда не получит некоторое оставшееся пространство, поскольку оно всегда сжимается до размера, необходимого всем элементам вместе

0 голосов
/ 29 января 2020
...
...
<LinearLayout
   android:id="@+id/layout_count"
   android:layout_width="200dp"
   or android:layout_width="match_parent
   android:layout_height="wrap_content"
   android:orientation="vertical">

   <LinearLayout
       android:layout_width="match_parent"
       android:layout_height="wrap_content"
       android:orientation="horizontal"
       android:gravity="center_vertical">

       <ImageView
           android:layout_width="wrap_content"
           android:layout_height="wrap_content"
           android:src="@drawable/ic_complete" />

       <TextView
           android:layout_width="match_parent"
           android:layout_weight="1"
           android:gravity="center"
           android:layout_height="wrap_content"
           android:text="1" />

      <ImageView
           android:layout_width="wrap_content"
           android:layout_height="wrap_content"
           android:src="@drawable/ic_complete" />

   </LinearLayout>

   <LinearLayout
       android:layout_width="match_parent"
       android:layout_height="wrap_content"
       android:orientation="horizontal"
       android:gravity="center_vertical">

       <ImageView
           android:layout_width="wrap_content"
           android:layout_height="wrap_content"
           android:src="@drawable/ic_complete" />

       <TextView
           android:layout_width="match_parent"
           android:layout_weight="1"
           android:gravity="center"
           android:layout_height="wrap_content"
           android:text="1" />

      <ImageView
           android:layout_width="wrap_content"
           android:layout_height="wrap_content"
           android:src="@drawable/ic_complete" />

   </LinearLayout>

</LinearLayout>
...