Android создание макета выровненных полей

#android #layout #alignment #android-edittext

#Android #макет #выравнивание #android-edittext

Вопрос:

Вот моя проблема: у меня есть логин, и я хочу выровнять поля EditText. Смотрите прикрепленное изображение макета Выравнивание редактируемых текстовых полей.
Я перепробовал несколько способов и не могу понять, как составить линейку полей.

Я действительно ненавижу макеты в Android, я трачу больше времени, просто возясь с вещами, чтобы выстроить их правильно. Хотелось бы, чтобы они просто отказались от него и использовали что-то более интуитивно понятное, поскольку это больше похоже на использование таблиц в HTML. Итак, заранее спасибо за вашу помощь и приветствия!

Комментарии:

1. Понимаю ваше разочарование, также мне понравился способ Android, который обрабатывает все элементы макета в xml отдельно от кода. Два поля редактирования уже выровнены, можете ли вы уточнить, что вы хотите?

2. @bob я думаю, что это рисунок из paintbrush, а не скриншот действия Android: P

3. Да, это эскиз с использованием Wireframessketcher, лучшего инструмента для предварительной сборки экранов и показа их клиенту, чтобы показать поток экрана и дизайн, стоимостью 75,00 долларов.

Ответ №1:

Вероятно, вы могли бы поиграть с RelativeLayout и получить именно то, что вы хотите.

Вот примерное использование TableLayout.

 <?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">
    <TableLayout
        android:layout_marginTop="40dip"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center">
        <TableRow>
            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:gravity="right"
                android:padding="10dip"
                android:text="UserID:" />
            <EditText
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:padding="10dip"
                android:text="USER ID" />
        </TableRow>
        <TableRow>
            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:gravity="right"
                android:padding="10dip"
                android:text="Password:" />
            <EditText
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:padding="10dip"
                android:text="PASSWORD" />
        </TableRow>
    </TableLayout>
    <LinearLayout
        android:layout_marginTop="50dip"
        android:orientation="horizontal"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:weightSum="3"
        android:gravity="center">
        <Button
            android:layout_width="0dip"
            android:layout_height="fill_parent"
            android:layout_weight="1"
            android:text="LOGIN" />
        <Button
            android:layout_width="0dip"
            android:layout_height="fill_parent"
            android:layout_weight="1"
            android:text="REGISTER" />
    </LinearLayout>
</LinearLayout>
  

Комментарии:

1. Спасибо, что сработало! Что бы я делал без stackoverflow, этот сайт лучший. Приветствую!

2. Единственная проблема с этим заключается в том, что поля EditText динамически изменяются при добавлении или удалении текста. Удалите оба текста в полях, и поле edittext на лету изменит размер до ширины в один символ.

3. Измените атрибут layout_width в EditTexts на fill_parent.

Ответ №2:

Посмотрите, работает ли это для вас. Он не совсем идеально центрируется, но хорошо выравнивается для разных размеров экрана.

     <?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
  xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent" android:background="#FFFF0000">
  <LinearLayout android:id="@ id/top_row"
            android:layout_height="wrap_content" 
            android:layout_alignParentTop="true"
            android:orientation="vertical" android:layout_centerHorizontal="true" android:layout_width="wrap_content" android:layout_marginTop="25dip">
            <LinearLayout  android:layout_height="wrap_content"  android:orientation="horizontal" android:layout_width="fill_parent">
                <TextView android:layout_height="wrap_content" android:text="User Id" android:gravity="right" android:layout_marginRight="10dip" android:layout_width="fill_parent" android:layout_weight="2" android:textColor="#FF000000"></TextView>
                <EditText android:layout_height="wrap_content" android:layout_width="fill_parent" android:ems="10" android:layout_weight="1"></EditText>
            </LinearLayout>
            <LinearLayout  android:layout_height="wrap_content"  android:orientation="horizontal" android:layout_width="fill_parent">
                <TextView android:layout_height="wrap_content" android:text="Password" android:gravity="right" android:layout_marginRight="10dip" android:layout_width="fill_parent" android:layout_weight="2" android:textColor="#FF000000"></TextView>
                <EditText android:layout_height="wrap_content" android:layout_width="fill_parent" android:ems="10" android:layout_weight="1"></EditText>
            </LinearLayout>
  </LinearLayout>
  <LinearLayout
            android:layout_height="wrap_content" 
            android:orientation="horizontal" android:layout_width="wrap_content" android:layout_below="@ id/top_row" android:layout_centerHorizontal="true" android:layout_marginTop="20dip">
        <Button android:layout_width="wrap_content" android:text="LOGIN" android:layout_height="wrap_content" android:layout_marginRight="10dip"></Button>
        <Button android:text="REGISTER" android:layout_height="wrap_content" android:layout_width="wrap_content" android:layout_marginLeft="10dip"></Button>
  </LinearLayout>
</RelativeLayout>
  

Вот как это выглядит в моей IDE…

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

Комментарии:

1. Понравился ваш подход, но я выбрал приведенный выше, поскольку кнопки выглядели немного чище.

Ответ №3:

Вы можете сделать это быстро и грязно, используя TableLayout, просто добавьте TableRow с TextView и EditText для идентификатора пользователя и повторите то же самое для пароля.

Смотрите http://developer.android.com/resources/tutorials/views/hello-tablelayout.html