Android studio textview multiline

400+ Android & Flutter Code

Example code for android + flutter app developers.

Tuesday, January 6, 2015

TextView new line (multiline) in android

TextView display text on android app. by default, TextView show text on a single line, and if it is long then TextView take more lines to display its text. android developers can generate a new line on TextView both programmatically and syntactically. android developers can make a multiline TextView without splitting text to multiline by android:minLines attribute.

the following android example code demonstrate us how can we syntactically create a new line on TextView widget by xml layout file and string resource file.

the simplest way to create a new line on TextView is android:text attribute. android:text attribute allow us to display text on android app. we can add a simple ‘\n’ to TextView text where we want to start a new line. in this way we can create a multiline TextView widget in android app. we can assign android:text attribute value by this way android:text=»Line1 \n Line2 \n Line3″ for a TextView widget. this value will display the specified TextView widget’s text on three lines. each ‘\n’ on TextView text generate a new line on TextView text.

another popular way to display text on TextView widget by referencing from string resource file. we can put a simple string name value pair on strings.xml file in res/values folder. then we can reference it to TextView widget by android:text attribute as android:text=»@string/Multiline_Text_By_N». finally the TextView widget will display text on android app from string resource file.

so, if we want to create a new line on Textview and if we also want to generate text from string resource file, then we can simply put ‘\n’ on string resource where we need a new line as example Line number 1 \nLine number 2 . this reference string will display two lines text on TextView.

android:minLines attribute allow us to set the minimum number of lines displayed in the TextView. if our text is small then TextView will display additional lines as blank line.

android:maxLines attribute allow us to set the maximum number of lines displayed in the TextView. if we break our text to 5 lines and set the android:maxLines attribute value to 3 then last 2 lines will be discarded (hide) from TextView widget.

TextView new line programmatically

this is the second example app of this tutorial. the following example code demonstrate us how can create a new line on Textview programmatically in java file.

android setText() method allow us to specify the text of TextView widget to display in android app. simply we can put an ‘\n’ on text where we want to create a new line as example setText(«Line1 \n Line 2»).

Append() method allow us to append text with TextView widget’s old text and finally display both old and appended text on TextView. we can append a android system line separator on TextView text where we want to start a new line then we can append next line’s text to TextView. so the specified TextView will display multiline text on android app.

Читайте также:  Паук для андроид 2012

android System class allow us to get the system related information and resources. System.getProperty(String propertyName) method allow us to get the value of a particular system property. so we can get the android system line separator as this way System.getProperty(«line.separator»).

we can generate TextView text from html formatted contents. so we can simply put a html ‘break’
tag in text where we want to start new line. finally we can set the TextView text as setText(Html.fromHtml(String)).

we also can populate TextView text from string resource file. to do this we can reference it as this way setText(R.string.Multiline_Text_By_N).

we also can declare a String variable and populate the string by mixing android line separator and text. finally we can set TextView text by setText(String) method. the TextView will display multiline text on android app.

Источник

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

мне понравилось внизу в xml

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

так что же я здесь делаю?

15 ответов

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

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

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

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

на android:singleLine=»false» работал отлично.

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

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

просто добавьте textview в ScrollView

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

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

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

надеюсь, что это помогает 🙂

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

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

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

заменить «\n» С Html equavalent «
» тогда звоните Html.fromHtml() в строке. Выполните следующие действия:

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

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

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

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

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

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

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

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

Источник

Drawing multiline text to Canvas on Android

Leveraging the Android framework and Kotlin to make Canvas text drawing more powerful

The Android Canvas offers a variety of drawing functions for implementing custom graphics in your app. A common use of Canvas is to draw text to a given region of a custom View , Drawable , Bitmap , etc.

Читайте также:  Получить деньги за android

Canvas has existing functions that allow you to draw text, the simplest of which can be seen below:

A single line of text is drawn at a given (x, y) origin, taking into account the properties of the Paint (to describe the colors and styles for the drawing eg. color , textSize , etc.). Other variants of this function exist that allow for specification of start and end positions within the text, drawing along a Path , etc.

The limitations of Canvas text drawing 🤨

The existing Canvas text drawing functions are simple and powerful but aren’t without their limitations. The major drawback (as mentioned above) is that the text is drawn on a single line. If the width of the text exceeds the width of the Canvas , the text will be clipped. Long text will usually need to be drawn on multiple lines, and you may have wanted “paragraph” style text in the first place. From here on, we’ll refer to this as multiline text.

How do we draw multiline text? 🤔

So how should we go about implementing this? Unfortunately you can’t just include \n characters in your text, as all whitespace characters are interpreted and drawn as spaces within the single line. Paint includes handy measureText and breakText functions for splitting up text which you could use. You may even consider an existing algorithm such as the Knuth-Plass Line Wrapping Algorithm. This quickly becomes a complex problem.

Android framework to the rescue 🚀

Thankfully, the Android framework provides us with a class that handles all of the complexity for us: Layout (in the android.text package), described as “a base class that manages text layout in visual elements on the screen”. It forms the basis of how classes like TextView fit text within given layout parameters.

The documentation stipulates:

For text that will be edited, use a DynamicLayout , which will be updated as the text changes. For text that will not change, use a StaticLayout .

Considering that we are trying to draw some static (multiline) text to Canvas, StaticLayout is just what we need!

Using StaticLayout 👨‍💻

Using StaticLayout is quite simple. Firstly, instantiate one by obtaining and using a StaticLayout.Builder :

A few parameters are required when obtaining the builder:

  • text : The text CharSequence to be laid out, optionally with spans
  • start : The index of the start of the text
  • end : The index + 1 of the end of the text
  • textPaint : The TextPaint used for layout
  • width : The bounding width (in pixels)

These parameters allow StaticLayout to layout the text appropriately within the bounding width . A resultant height property becomes available once the StaticLayout has been instantiated. Many other parameters can be appended to the builder to adjust the end appearance, but we’ll get to those later.

Note: StaticLayout.Builder was added in API Level 23. Prior to this, you need to use the StaticLayout constructors. To add to this, the constructors have been deprecated in API Level 28. Be sure to handle backwards compatibility appropriately.

Note: If you happen to be utilising this in the onDraw function of a custom View , be sure to instantiate the StaticLayout separately to avoid object allocation during drawing (in a constructor or Kotlin init block, for example).

A word on TextPaint ☝️

Before we progress, there’s one thing that needs to be discussed… What is TextPaint ? While almost all Canvas functions require a Paint parameter, StaticLayout requires a TextPaint . From the documentation, it is described as “an extension of Paint that leaves room for some extra data used during text measuring and drawing”. A great explanation can be found here. In short, you use it exactly as you would Paint and don’t have to worry about the extra data it includes (for the purpose of what we are doing).

Читайте также:  Android static context memory leak

Exploring the StaticLayout properties 🔍

Phew! We now know the basics of what StaticLayout is and how we can use it to draw multiline text to Canvas . However, there are a lot of parameters that you can provide to change the appearance of the end result.

Consider a basic text editor: you usually have options to change the alignment, margins, line spacing, text size and more. The same is true for StaticLayout ; additional parameters can be appended to the StaticLayout.Builder .

It is important to note that some parameters (like color ) do not belong directly to StaticLayout , but rather belong to the TextPaint . Let’s take a look at the some of the options we have:

alignment

The alignment of the text, similar to gravity.

Источник

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

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

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

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

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

Я попытался прокомментировать один из ответов выше, но у меня недостаточно репутации.
Я просто подумал, что добавлю, что если вы используете:

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

android:singleLine=»false» работал нормально.

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

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

Просто добавьте textview в ScrollView

Просто поместите ‘\ n’ внутри вашего текста … никакого дополнительного атрибута не требуется 🙂

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

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

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

Это сработало для меня. 1 – номер столбца.

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

Надеюсь это поможет 🙂

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

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

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

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

Источник

Оцените статью