2015-01-14 2 views
3

Если coloumn 3 имеет большой текст, столбец 2 исчезает. Столбец 2 также исчезает, если я установил android:stretchColumns="2,3". Я хотел бы установить minWidth s в столбец 2. Но этот атрибут игнорируется.Как сжать столбец TableLayout в minWidth?

Я помогаю себе прямо сейчас, установив android:stretchColumns="3" и android:shrinkColumns="3" и применение maxWidth к TextView на позиции 2. Это почти делает работу, но MinWidth будет больше подходит.

  <TableLayout 
       android:layout_width="0dp" 
       android:layout_height="match_parent" 
       android:layout_weight="1" 
       android:shrinkColumns="2,3" 
       android:stretchColumns="3" > 

       <TableRow 
        android:layout_width="wrap_content" 
        android:layout_height="wrap_content" > 

        <TextView 
         android:id="@+id/TextViewIdLabel" 
         style="@style/overlay_content" 
         android:text="@string/id_label" 
         android:textStyle="bold" /> 

        <TextView 
         android:id="@+id/TextViewIdValue" 
         style="@style/overlay_content" 
         android:layout_marginLeft="4dp" /> 

        <TextView 
         android:id="@+id/TextViewPersonIdLabel" 
         style="@style/overlay_content" 
         android:layout_marginLeft="8dp" 
         android:text="@string/person_id_label" 
         android:textStyle="bold" /> 

        <TextView 
         android:id="@+id/TextViewPersonIdValue" 
         style="@style/overlay_content" 
         android:layout_marginLeft="4dp" /> 
       </TableRow> 
       <!-- I skipped the other rows --> 
      </TableLayout> 

Это используемый стиль, если вам интересно:

<style name="overlay_content"> 
    <item name="android:textColor">@color/foreground_color_on_dark_background</item> 
    <item name="android:layout_width">wrap_content</item> 
    <item name="android:layout_height">wrap_content</item> 
    <item name="android:textSize">20sp</item> 
    <item name="android:ellipsize">marquee</item> 
    <item name="android:singleLine">true</item> 
</style> 

Update:

Как приходили ответы, я узнал больше о моих требованиях, которые я подытожены в этом комментарии : How to shrink a TableLayout column to a minWidth?

+0

Как насчет установки веса на столбец вместо 'android: shrinkColumns' и' android: stretchColumns'. Итак, для столбца 1 вы можете установить 0,2 вес, 0,3 для столбца 2 и 0,5 для столбца 3 и так далее? – Slartibartfast

+0

@Slartibartfast До сих пор ваше решение - единственная работа, которая всегда гарантирует, что все столбцы отображаются хотя бы частично. – OneWorld

ответ

3

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

Как насчет установки веса на столбец вместо android:shrinkColumns и android:stretchColumns. Итак, для столбца 1 вы можете установить 0,2 вес, 0,3 для столбца 2 и 0,5 для столбца 3 и т. Д.

2

Как сгустить k столбец TableLayout для minWidth?

Actually it is simple, just TextView layout_width="wrap_content" can do 
that, the reason not working in your style is that 'wrap_content' should 
not work together with TextView 'ellipsize', they are conflict. So you need 
one seperate syle 'overlay_slide' for the column that has long text. 

So use 'overlay_content' for columns those have short text, use  
'overlay_slide' for columns that have long text. 

Besides I suppose the 'ellipsize' in your style is not working because 
seems two items missing: 

    <item name="android:focusable">true</item> 
    <item name="android:focusableInTouchMode">true</item> 

finally in the column that has long text, you also need: 

    android:layout_weight="1" 

to use all rest of space for 'ellipsize'. 


Удалить android:shrinkColumns="2,3" android:stretchColumns="3" из TableLayout


Solution работает стили и расположение:

//remove 'ecllipze' related items from 'overlay_content' 
<style name="overlay_content"> 
    <item name="android:textColor">@color/foreground_color_on_dark_background</item> 
    <item name="android:layout_width">wrap_content</item> 
    <item name="android:layout_height">wrap_content</item> 
    <item name="android:textSize">20sp</item>  
</style> 

//remove 'android:layout_width' from 'overlay_slide' 
<style name="overlay_slide"> 
    <item name="android:textColor">@color/foreground_color_on_dark_background</item> 
    <item name="android:layout_height">wrap_content</item> 
    <item name="android:textSize">20sp</item> 
    <item name="android:ellipsize">marquee</item> 

    <item name="android:focusable">true</item> 
    <item name="android:focusableInTouchMode">true</item> 

    <item name="android:singleLine">true</item> 
</style> 


<TableLayout 
xmlns:android="http://schemas.android.com/apk/res/android" 
android:layout_width="match_parent" 
android:layout_height="wrap_content" 

> 

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

     <TextView 
      android:id="@+id/TextViewIdLabel" 
      style="@style/overlay_content"    
      android:text="@string/id_label" 
      android:textStyle="bold" /> 

     <TextView 
      android:id="@+id/TextViewIdValue" 
      style="@style/overlay_content" 
      android:layout_marginLeft="4dp"/> 

     <TextView 
      android:id="@+id/TextViewPersonIdLabel" 
      style="@style/overlay_content" 
      android:layout_marginLeft="8dp" 
      android:text="@string/person_id_label" 
      android:textStyle="bold"/> 

     <TextView 
      android:id="@+id/TextViewPersonIdValue" 
      style="@style/overlay_slide" 
      android:layout_weight="1" 
      android:layout_marginLeft="4dp" /> 

    </TableRow> 
</TableLayout> 


Скриншот из моего тестирования: (портрет и пейзаж)

My test long text column is text 'Column 1 ... Column 8' 

In Portrait In landscape

+0

Столбец 3 исчезнет тогда, если другие столбцы слишком велики. – OneWorld

+0

Итак, ваш 'TextView' скользящий' marquee 'не работает? то вам нужно дать фиксированную ширину для «TextView» столбца 3, чтобы выполнить скользящую работу. – Xcihnegn

+0

Вы также можете попробовать, чтобы все столбцы имели ширину 'TextView'' android: layout_weight = "1" ' – Xcihnegn

0

Вы не можете изменить ширину столбца таким образом. Ширина определяется только самой широкой строкой в ​​этом столбце. Если у вас нет дисплея, ширина не будет. Вы можете отрегулировать это, отрегулировав текст для этой строки.

<TextView 
      android:id="@+id/TextViewIdValue" 
      style="@style/overlay_content" 
      android:layout_marginLeft="4dp" 
      android:minEms="4"    <!-- You can use either of these --> 
      android:minWidth="40dp" /> 

Компромисс здесь является то, что вы могли бы бежать из комнаты и другие ваши колонки будут работать с конца, но вы можете настроить размер шрифта, чтобы исправить это, даже если вам придется переписывать свой стиль с android:textSize="10dp"

Этот код работает для меня, но я также изменил ширину таблицы TableLayout с "0dp" на "match_parent".

<TableLayout 
android:layout_width="match_parent" 
android:layout_height="match_parent" 
android:layout_weight="1" 
android:shrinkColumns="3" 
android:stretchColumns="*" > 

<TableRow 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" > 

    <TextView 
     android:id="@+id/TextViewIdLabel" 
     style="@style/overlay_content" 
     android:text="id_label" 
     android:textStyle="bold" /> 

    <TextView 
     android:id="@+id/TextViewIdValue" 
     style="@style/overlay_content" 
     android:layout_marginLeft="4dp" 
     /> 

    <TextView 
     android:id="@+id/TextViewPersonIdLabel" 
     style="@style/overlay_content" 
     android:layout_marginLeft="8dp" 
     android:text="person_id_label" 
     android:textSize="10dp" 
     android:textStyle="bold" 
     android:minEms="4" 
     android:minWidth="40dp" /> 
    <!-- You can use either of these --> 

    <TextView 
     android:id="@+id/TextViewPersonIdValue" 
     style="@style/overlay_content" 
     android:layout_marginLeft="4dp" /> 
</TableRow> 
<!-- I skipped the other rows --> 

+0

Вы применили 'minWidth' to column 1. Но я говорил о столбце 2, который исчезает, когда столбец 3 большой. Есть 4 столбца 0, 1, 2 и 3. – OneWorld

+0

Я думаю, что я неправильно понял вопрос. Вы пытаетесь получить все столбцы равными? Должна ли быть усадка в колонке 2? Из того, что, как мне кажется, я понимаю, вы можете либо пойти с помощью метода 'maxWidth', указав, что этот столбец растягивается, а не усаживается, или используйте метод веса, который они предлагают. – DevJem

+0

Я хотел использовать пространство максимально эффективно. Я думал, что «shrinkColumns» является хорошей собственностью для достижения этой цели. Однако 'shrinkColumns' и' stretchColumns' могут привести к исчезновению столбцов. Что-то, чего я, конечно, не хочу. Вот почему я попытался совместить 'shrinkColumn' с' minWidth'. Однако 'minWidth' не распознается' TableLayout'. Вот почему я задал этот вопрос. Тогда Slartibartfast напугала меня на правильном пути. Он предложил избегать использования свойств 'shrinkColumns' /' stretchColumns' и вместо этого использовать 'weight'. Кажется, это лучшее решение для моих нужд. – OneWorld