Подтвердить что ты не робот

Textview с длинным текстом выталкивает другие виды в GridLayout, несмотря на то, что eellipsize = end

Моя проблема очень похожа на Как получить макет, где один текст может расти и эллипсироваться, но не сожрать другие элементы на макете, но читать дальше ниже, почему я не могу использовать TableLayouts, как предлагалось там.

Я пытаюсь создать строку listview, которая выглядит примерно так:

| TextView | Просмотреть 1 | Просмотр 2 |

Все представления содержат элементы переменной ширины. TextView имеет значение ellipsize = "end". Вид 1 должен совпадать слева от TextView, а View 2 - в правой части экрана. Таким образом, обычно между пробелами между View 1 и View 2 будет пробел. Поскольку текст в TextView увеличивается дольше, TextView должен расти, нажав View 1 вправо, пока не останется больше пробелов. Затем нужно эллипсизовать, разрезать текст в TextView и добавить в конце многоточие ( "..." ).

Итак, результат должен выглядеть примерно так:

+----------------------------------------+
| short text [view1]             [view2] |
+----------------------------------------+
| long text with ell ... [view1] [view2] |
+----------------------------------------+

Я пробовал:

  • TableLayouts, но они, похоже, очень медленно прокручиваются на некоторых устройствах.
  • RelativeLayouts, но у меня либо были перекрывающиеся представления, либо view1 или view2 полностью исчезли.
  • GridLayouts, но TextView всегда растет до тех пор, пока он не займет всю ширину экрана, таким образом нажав view1 и view2 на экран.

Это GridLayout, который я пробовал:

<GridLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content" >

    <TextView
        android:layout_gravity="left|fill_horizontal"
        android:ellipsize="end"
        android:singleLine="true"
        android:text="Long text to demonstrate problem with TextView in GridLayout taking up too much space despite ellipsis" />

    <TextView
        android:layout_gravity="left"
        android:text="(view1)" />

    <TextView
        android:layout_gravity="right"
        android:text="(view2)" />
</GridLayout>

View 1 и View 2 на самом деле не являются TextViews, я просто использовал их в этом примере для упрощения.

Есть ли способ достичь этого, не используя TableLayouts?

EDIT: По просьбе, вот моя попытка решить это с помощью RelativeLayout. TextView обрабатывает всю ширину экрана в этом случае, поэтому не видны view1 или view2.

<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content" >

    <TextView
        android:id="@+id/rl0"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:ellipsize="end"
        android:singleLine="true"
        android:text="Long text to demonstrate problem with TextView in GridLayout taking up too much space despite ellipsis" />

    <TextView
        android:id="@+id/rl1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_toRightOf="@id/rl0"
        android:layout_marginLeft="10dp"
        android:text="(view1)" />

    <TextView
        android:id="@+id/rl2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_toRightOf="@id/rl1"
        android:layout_alignParentRight="true"
        android:layout_marginLeft="10dp"
        android:text="(view2)" />
</RelativeLayout>
4b9b3361

Ответ 1

Кажется, я нашел потенциальное решение для предотвращения неограниченного расширения TextView в GridLayout и вытеснения других представлений. Не уверен, что это было зарегистрировано ранее.

Вам нужно использовать fill_gravity fill и установить произвольную макетную ширину или ширину для длинного TextView, нуждающегося в эллипсировании.

android:layout_gravity="fill"
android:layout_width="1dp"

Работает как для GridLayout, так и для android.support.v7.widget.GridLayout

Ответ 2

Я большой поклонник LinearLayouts, поэтому здесь мое предложение:

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

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:layout_weight="1" >

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:ellipsize="end"
            android:singleLine="true"
            android:text="Long text to demonstrate problem with TextView in GridLayout taking up too much space despite ellipsis" />

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="(view1)" />
    </LinearLayout>

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="right"
        android:text="(view2)" />
</LinearLayout>

Ответ 3

Я предлагаю вам играть с свойством layout_weight вашего виджета

Пример:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity" >

    <LinearLayout
    android:layout_width="fill_parent"
    android:layout_height="wrap_content" 
    android:orientation="horizontal"
    android:weightSum="10">

    <LinearLayout
       android:id="@+id/ll_twoViewContainer"
       android:layout_weight="8"
       android:layout_width="0dp"
       android:layout_height="wrap_content" 
       android:orientation="horizontal">

      <TextView
          android:id="@+id/rl0"
          android:layout_width="wrap_content"
          android:layout_height="wrap_content"
          android:layout_alignParentLeft="true"
          android:layout_weight="1"
          android:ellipsize="end"
          android:singleLine="true"
          android:text="Long text" />

      <TextView
          android:id="@+id/rl1"
          android:layout_width="wrap_content"
          android:layout_height="wrap_content"
          android:layout_marginLeft="10dp"
          android:layout_toRightOf="@id/rl0"
          android:layout_weight="1"
          android:minWidth="120dp"
          android:text="(view1)" />

    </LinearLayout>
    <TextView
        android:id="@+id/rl2"
        android:layout_weight="2"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_toRightOf="@id/rl1"
        android:layout_alignParentRight="true"
        android:layout_marginLeft="10dp"
        android:text="(view2)" />
  </LinearLayout>

</LinearLayout>

Наконец, ваш макет будет выглядеть следующим образом:

+----------------------------------------+
| short text [view1]             [view2] |
+----------------------------------------+
| long text with ell ... [view1] [view2] |
+----------------------------------------+

Ответ 4

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

Ответ 5

Трюк, который работал у меня, заключался в использовании maxWidth для ограничения ширины первого представления. Вам нужно сделать это с помощью Java, вот основная логика:

firstView.setMaxWidth(parentView.getWidth() - view2.getWidth() - view1.getWidth() - padding * 2);

Не очень, но он работает.

Ответ 6

Я думаю, что в макете есть только небольшая проблема, которая может быть решена, привязав view3 вправо и начинать оттуда, чтобы заставить представление иметь ограниченную область (следовательно, возможность правильно установить эллипс):

<?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="wrap_content">
<TextView
        android:id="@+id/rl3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:text="(view2)" />
<TextView
        android:id="@+id/rl2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_toLeftOf="@id/rl3"
        android:text="(view1)" />
<TextView
        android:id="@+id/rl1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:ellipsize="end"
        android:singleLine="true"
        android:layout_alignParentLeft="true"
        android:layout_toLeftOf="@id/rl2"
        android:text="Long text to demonstrate problem with TextView in GridLayout taking up too much space despite ellipsis" />
</RelativeLayout>

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

Привет!

Ответ 7

Попробуйте это

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

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_weight="1"
        android:gravity="center">
       <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:ellipsize="end"
            android:singleLine="true"
            android:text="Long text to demonstrate problem with TextView in GridLayout taking up too much space despite ellipsis"/>
    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_weight="1"
        android:gravity="center">
        <TextView
             android:layout_width="wrap_content"
             android:layout_height="wrap_content"
             android:layout_gravity="left"
             android:text="(view1)"/>
    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_weight="1"
        android:gravity="center">
        <TextView
             android:layout_width="wrap_content"
             android:layout_height="wrap_content"
             android:layout_gravity="right"
             android:text="(view2)"/>
    </LinearLayout>

</LinearLayout>

В настоящее время все представления центрированы. Вы можете изменить свойство android:gravity для удовлетворения ваших потребностей. Например, вы можете захотеть выровнять view1 вправо и view2 слева, в этом случае последние два LinearLayout будут выглядеть примерно так (с краем 5dp справа и слева соответственно):

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_weight="1"
    android:gravity="center|right">
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="left"
        android:layout_marginRight="5dp"
        android:text="(view1)"/>
</LinearLayout>

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_weight="1"
    android:gravity="center|left">
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="right"
        android:layout_marginLeft="5dp"
        android:text="(view2)"/>
</LinearLayout>

Ответ 8

Я нахожу свое решение для случая номер 2 (тот, у которого длинный текст):

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:weightSum="3" >

    <TextView
        android:id="@+id/rl0"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight="3"
        android:ellipsize="end"
        android:singleLine="true"
        android:text="Long text to demonstrate problem with TextView in GridLayout taking up too much space despite ellipsis" />

    <TextView
        android:id="@+id/rl1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="10dp"
        android:layout_weight="1"
        android:text="(view1)" />

    <TextView
        android:id="@+id/rl2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="10dp"
        android:layout_weight="1"
        android:text="(view2)" />

</LinearLayout>

Реальная проблема - случай один, и я не пробовал много чего для этого. Я надеюсь, что это поможет (и если у меня будет больше свободного времени, я постараюсь добиться первого!).

Ответ 9

Если представления справа перетаскиваются текстом по дизайну, вы можете также использовать ListView вместо GridView.

Вам просто нужно сделать базу макета списка элементов RelativeLayout и установить такие правила:

  • Вы можете установить два вида справа: alignParentRight (с помощью android: layout_alignParentLeft = "true" ), но убедитесь, что первый вид остается слева от второго, поэтому он будет нажимать себя налево, как взгляды растягиваются.

  • Вы можете сделать TextView слева выравниванием слева, но оставайтесь слева от первого представления (используя android: layout_toLeftOf = "@+ id/viewId" ), чтобы он не перекрывался с просмотров.

Ответ 10

Попробуйте использовать вес макета

   <TableRow
        android:id="@+id/tableRow3"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignBottom="@+id/tableRow2"
        android:layout_alignParentBottom="true"
        android:gravity="center"
        android:weightSum="10"
        android:background="@android:color/black" >

        <TextView
            android:id="@+id/txtInningsTotal"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="2"
            android:gravity="center"
            android:text="0" 
            android:textColor="@android:color/white" />

        <TextView
            android:id="@+id/txtTeamOneTotal"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="2.5"
            android:gravity="center"
            android:text="0" 
            android:textColor="@android:color/white" />

        <View
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="0.2" />

        <TextView
            android:id="@+id/txtTeamTwoTotal"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="2.5"
            android:gravity="center"
            android:text="0"
            android:textColor="@android:color/white"  />

        <View
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="0.2" />

        <TextView
            android:id="@+id/txtGrandTotal"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="3"
            android:gravity="center"
            android:text="0"
            android:textColor="@android:color/white"  />
    </TableRow>

Здесь я взял таблицу, в которой есть сумма веса макета, которая составляет 10, означает, что она равна 100% своей родительской. и во всех его дочерних представлениях я установил ширину в 0Dp и дал вес 1 или 2. так что это займет до этого процента от общего количества 10. так что макет будет соответствующим образом скорректирован на экране, а также не будет проблем с перекрытием,

Если вы правильно поняли, тогда это ваш ответ.

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

Ответ 11

Во-первых, вы должны выполнить макет [view 2] родительскому правилу;

Опять же, вы ссылаетесь на ссылку на два последних макета!

<Relativelayout android:layout_width="match_parent"
            android:layout_height="wrap_content"
      <TextView
        android:id="@+id/view2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
       />

      <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_toLeft="@id/view2"
        android:gravity="left">

        <TextView
            android:id="@+id/shortORlongtTextView"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_toRightOf="@id/view1"
            android:ellipsize="end"
            android:maxLines="1"
            android:textSize="18dp"/>

        <TextView
            android:id="@+id/view1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentRight="true"
           />
    </RelativeLayout>

Ответ 12

У меня была такая же проблема с макетом сетки. то, что я сделал, задана фиксированная ширина для текстового вида, а также задано свойство layout_columnWeight для каждого текстового вида, тогда проблема была исправлена, надеюсь, что это поможет...

           <TextView
                android:id="@+id/txtName"
                style="@style/MyDetailTitle"
                android:layout_width="@dimen/detail_length"
                android:layout_height="wrap_content"
                android:text="@string/app_name"
                app:layout_column="3"
                app:layout_columnWeight="1"
                app:layout_gravity="start"
                app:layout_row="1" />