Как выстроить вывод intger в пользовательском диалоге Android - PullRequest
0 голосов
/ 14 апреля 2011

Я отображаю целочисленные данные из базы данных SQLite, используя SimpleCursorAdaptor. Все появляется, но выравнивание все неправильно: enter image description here

Диалог выглядит так:

    <?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">

   <ListView android:id="@+id/lvwScores"
       android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>
    <Button
     android:id="@+id/btnOK "
     android:layout_height="wrap_content"
     android:layout_width="wrap_content"
     android:text="OK" android:layout_below="@id/lvwScores">
   </Button>
</RelativeLayout>

С файлом строки XML:

<?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">
<TableLayout  android:layout_width="fill_parent" android:layout_height="wrap_content" android:stretchColumns="0,1,2,3">
<TableRow >
<TextView android:id="@+id/tvwPlayer1Score" xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content" android:layout_height="wrap_content" android:gravity="right"/>
<TextView android:id="@+id/tvwPlayer2Score" xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content" android:layout_height="wrap_content" android:gravity="right"/>
<TextView android:id="@+id/tvwPlayer3Score" xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content" android:layout_height="wrap_content" android:gravity="right"/>
<TextView android:id="@+id/tvwPlayer4Score" xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content" android:layout_height="wrap_content" android:gravity="right"/>
</TableRow>
</TableLayout>
</RelativeLayout>

Ответы [ 2 ]

1 голос
/ 14 апреля 2011

TableLayout - плохой выбор. Из-за присущей ей текучести столбцы будут различаться по ширине в зависимости от содержимого внутри них (хотя растяжение минимизирует это), которое вы не можете контролировать (см. Ниже). Кроме того, объявление пространства имен должно быть только в корневом элементе XML, а не в каждом;)

Значительно упростите макет строки, используя вместо этого:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="fill_parent"
  android:layout_height="wrap_content"
  android:orientation="horizontal">
  <TextView android:id="@+id/tvwPlayer1Score"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_weight="1"
    android:gravity="right"/>
  <TextView android:id="@+id/tvwPlayer2Score"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_weight="1"
    android:gravity="right"/>
  <TextView android:id="@+id/tvwPlayer3Score"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_weight="1"
    android:gravity="right"/>
  <TextView android:id="@+id/tvwPlayer4Score"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_weight="1"
    android:gravity="right"/>
</LinearLayout>

Комбинация layout_width="fill_parent" и layout_weight="1" на каждом элементе говорит системе разместить все четыре элемента, расположенные на одинаковом расстоянии (поскольку они имеют одинаковую весовую сумму), чтобы заполнить строку. Я почти всегда использую вложенный LinearLayout вместо TableLayout всякий раз, когда это возможно (это все TableLayout на самом деле так или иначе).

Еще одна вещь из строки XML, которую вы опубликовали: неправильно устанавливать корневой элемент макета элемента списка с помощью layout_height=fill_parent, как в теге RelativeLayout. В зависимости от того, где нарисован этот макет, менеджер макетов может фактически прослушать вас, и одна строка может в итоге занять все окно!

ПРИМЕЧАНИЕ О ТАБЛИЦЕ ПАРАМЕТРОВ:

Если вы настаиваете на том, чтобы придерживаться TableLayout, знайте, что вы можете (и должны) опускать все атрибуты layout_width и layout_height для каждого дочернего элемента TableLayout и TableRow. Эти два виджета игнорируют то, что вы говорите, и устанавливают значения их дочерних элементов равными MATCH_PARENT и WRAP_CONTENT (соответственно), поэтому добавление их в ваш код будет только сбивать вас с толку, если вы думаете, что они должны вступить в силу.

Надеюсь, что поможет!

1 голос
/ 14 апреля 2011

Вы должны указать атрибут android:gravity:

<TextView android:gravity="right" />

Подробнее об этом: Android TextView

Обновление:

Я немного изменил макет row.xml.

  • изменил ширину TextViews 'на fill_parent (они растянуты во всяком случае, так что это не должно причинить вреда), и
  • добавил некоторые атрибуты к TableRow тег

Так это выглядит так:

[...]
<TableRow android:orientation="horizontal" 
    android:layout_width="fill_parent" android:layout_height="match_parent">
    <TextView android:id="@+id/tvwPlayer1Score"
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="fill_parent" android:layout_height="wrap_content"
        android:gravity="right" />
    <TextView android:id="@+id/tvwPlayer2Score"
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="fill_parent" android:layout_height="wrap_content"
        android:gravity="right" />
    <TextView android:id="@+id/tvwPlayer3Score"
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="fill_parent" android:layout_height="wrap_content"
        android:gravity="right" />
    <TextView android:id="@+id/tvwPlayer4Score"
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="fill_parent" android:layout_height="wrap_content"
        android:gravity="right" android:layout_margin="2dp" />
</TableRow>
[...]

И вывод выглядит прямо сейчас:

table row

Пожалуйста, дайте мне знать, если это помогло (все еще очень смущенно ...)

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