Home > database >  How do multiline text in Android
How do multiline text in Android

Time:11-29

I am practing Android trying to make a simple App, with multiline text..

I tried writing the text how I know how to from kivy, and I read this sometime before, using

"""
text\n
another text
"""

Here's the textView Code:

    <TextView
        android:id="@ id/textView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="68dp"
        android:text=
            """
            onCreate(): Called by the OS when the activity is first created.\n
            This is where you initialize any UI elements or data objects.\n
            You also have the savedInstanceState of the activity that contains its previously saved state, and you can use it to recreate that state.
            """
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.498"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@ id/textView2" />

it doesn't seem to work, and I tried writng it plainly, like: "Text\n Another Text" and it works, but this can be really difficult to go through, is you are working with really long texts..

just in case, Here's the textView code to the second way I tried:

    <TextView
        android:id="@ id/textView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="68dp"
        android:text="onCreate(): Called by the OS when the activity is first created. This is where you initialize any UI elements or data objects. You also have the savedInstanceState of the activity that contains its previously saved state, and you can use it to recreate that state."
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.498"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@ id/textView2" />

Is there a way I can write it similar to the first way I wrote it? Do I need to use another type of text or add something to this one? And is there something I'm doing wrong that's making the first way wrong.?

CodePudding user response:

It's bad practice to have hard coded string in your layout xml files.

You can define strings in a separate strings.xml which should already be generated in a default android project under res/values/strings.xml

Here you can just define strings and use newlines in the string however you want.

for example

<string name="myString" > This is your string.

   This is the second line of your string.\n\n Third line of your string.</string>

you can either use actual new lines or \n in this.

and then assign it to the TextView like

 android:text="@string/myString"
  • Related