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

Многострочный TextView в Android?

Мне понравилось ниже в xml

<TableRow>
    <TextView android:id="@+id/address1"
        android:layout_width="fill_parent" 
        android:layout_height="wrap_content"
        android:gravity="left"
        android:maxLines="4" 
        android:singleLine="false"              
        android:text="Johar Mor, Gulistan-e-Johar, Karachi" >
    </TextView> 
</TableRow>

Он не работает для multiline, и я использую TableLayout...

так что я ошибаюсь здесь?

4b9b3361

Ответ 1

Если текст, который вы помещаете в TextView, короткий, он не будет автоматически расширяться до четырех строк. Если вы хотите, чтобы в TextView всегда было четыре строки независимо от длины текста, установите атрибут android:lines:

<TextView
    android:id="@+id/address1"
    android:gravity="left"
    android:layout_height="fill_parent"
    android:layout_width="wrap_content"
    android:maxLines="4"
    android:lines="4"
    android:text="Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat."></TextView>

Вы можете сделать это с помощью TableRow, см. Ниже код

<TableRow >
        <TextView
            android:id="@+id/tv_description_heading"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:gravity="left"
            android:padding="8dp"
            android:text="@string/rating_review"
            android:textColor="@color/black"
            android:textStyle="bold" />

        <TextView
            android:id="@+id/tv_description"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:gravity="left"
            android:maxLines="4"'enter code here'
            android:padding="8dp"
            android:text="The food test was very good."
            android:textColor="@color/black"
            android:textColorHint="@color/hint_text_color" />
    </TableRow>

Ответ 2

Я просто подумал, что добавлю это, если вы используете:

android:inputType="textMultiLine"

Тогда представление перестает быть кликабельным. Я пытался получить многострочные текстовые просмотры в меню слайдера, которые, очевидно, должны реагировать на клики.

android:singleLine="false" работал нормально, хотя.

Ответ 3

Мне не нравится ни один из ответов. Просто установите inputType, и TextView будет адаптироваться к его содержимому

<TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:inputType="textMultiLine"/>

Протестировано на Nexus One (2.3) и Nexus 4 (4.4)

Ответ 4

Просто добавьте текстовое представление в ScrollView

<ScrollView
           android:layout_width="fill_parent"
           android:layout_height="wrap_content"
           android:layout_weight="1"
           android:layout_marginLeft="15dp"
           android:layout_marginRight="15dp"
           android:layout_marginTop="20dp"
           android:fillViewport="true">

           <TextView
               android:id="@+id/txtquestion"
               android:layout_width="fill_parent"
               android:layout_height="match_parent"
               android:background="@drawable/abs__dialog_full_holo_light"
               android:lines="20"
               android:scrollHorizontally="false"
               android:scrollbars="vertical"
               android:textSize="15sp" />

       </ScrollView>

Ответ 5

Просто поместите '\n' внутри вашего текста... не требуется дополнительный атрибут:)

          <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textAppearance="?android:attr/textAppearanceLarge"
            android:text="Pigeon\nControl\nServices"
            android:id="@+id/textView5"
            android:layout_gravity="center"
            android:paddingLeft="12dp"/> 

Ответ 6

Мне не нравится решение, которое заставляет количество строк в текстовом представлении. Я скорее предлагаю вам решить его с помощью предлагаемого здесь решения . Поскольку я вижу, что OP также борется с тем, чтобы текстовое представление выглядело как правильно в таблице, а shrinkColumns - правильная директива для перехода, чтобы достичь желаемого.

Ответ 7

Попытайтесь работать с EditText, сделав его незаметным и нецелесообразным, также вы можете отобразить полосу прокрутки и удалить подстроку EditText.
Вот пример:

<EditText
android:id="@+id/my_edit_text"
android:layout_width="match_parent"
android:layout_height="wrap_parent"
android:inputType="textMultiLine"                   <!-- multiline -->
android:clickable="false"                         <!-- unclickable -->
android:focusable="false"                         <!-- unfocusable -->
android:scrollbars="vertical"     <!-- enable scrolling vertically -->
android:background="@android:color/transparent"   <!-- hide the underbar of EditText -->
/>  

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

Ответ 8

Лучший ответ, который я нашел для многострочного TextView:

android:inputType="textMultiLine"

Ответ 9

То, что я узнал, заключалось в том, чтобы добавить "\n" между словами, в которых вы хотите, чтобы он затормозил в следующей строке. Например...

<TextView
    android:id="@+id/time"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:textAlignment="center"
    android:text="M-F 9am-5pm \n By Appointment Only" />

\n между 5pm и By позволило мне больше контролировать, где я хочу, чтобы моя следующая строка начиналась и заканчивалась.

Ответ 10

Сначала замените "\n" на Html equavalent "&lt;br&gt;" затем вызовите Html.fromHtml() в строке. Выполните следующие шаги:

String text= model.getMessageBody().toString().replace("\n", "&lt;br&gt;")
textView.setText(Html.fromHtml(Html.fromHtml(text).toString()))

Это работает отлично.

Ответ 11

Вы можете использовать Android: inputType = "textMultiLine"

  <TextView android:id="@+id/address1"
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content"
    android:gravity="left"
    android:maxLines="4" 
    android:inputType="textMultiLine"
    android:text="Johar Mor, Gulistan-e-Johar, Karachi" />

Ответ 12

Я использовал:

TableLayout tablelayout = (TableLayout) view.findViewById(R.id.table);
tablelayout.setColumnShrinkable(1,true);

это сработало для меня. 1 - номер столбца.

Ответ 13

You can do this with TableRow, see below code

<TableRow >
    <TextView
        android:id="@+id/tv_description_heading"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:gravity="left"
        android:padding="8dp"
        android:text="@string/rating_review"
        android:textColor="@color/black"
        android:textStyle="bold" />

    <TextView
        android:id="@+id/tv_description"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:gravity="left"
        android:maxLines="4"'enter code here'
        android:padding="8dp"
        android:text="The food test was very good."
        android:textColor="@color/black"
        android:textColorHint="@color/hint_text_color" />
</TableRow>

Ответ 14

Почему бы вам не объявить строку вместо написания длинных строк в файле макета. Для этого вам нужно объявить строку кода в файл макета "android: text =" @string/text "и перейти в \\app\src\main\res\values ​​\ strings.xml и добавить строку кода" Ваш многострочный текст здесь "Также используйте" \n", чтобы разбить строку из любой точки, в которой линия будет автоматически отрегулирована.

Ответ 15

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

Я поместил 4 текстовых просмотра в вертикальное линейное расположение.

<Linearlayout
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation:"vertical"

    ...>
    <TextView
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:text:"line1"
       .../>
    <TextView
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:text:"line2"
       .../>
    <TextView
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:text:"line3"
       .../>
    <TextView
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:text:"line4"
       .../>
</LinearLayout>

Это решение подходит для случаев, когда текстовое представление текста является постоянным, например, метки.

Ответ 16

TextView будет многострочной, если в одной строке не будет достаточно места, а singLine не будет установлено в true.

Если он получает пробел в одной строке, он не будет многострочным.