Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android TextView new line isn't working

Tags:

java

android

I found the Answer I will accept it in 2 days time

I have been trying to create an activity that can display multiple messages for the user, in order to fit everything in the text view I need to create three lines. My search online hasn't given me any solutions, here is what I have tried

Java

"\n"
"\r\n"
newLineChar = System.getProperty("line.separator")
messageTextView.setText(Html.fromHtml("This\n Is\n A Test"));
messageTextView.setText(Html.fromHtml("This<br> Is<br> A Test"));

xml

android:lines="3"
android:maxLines="3"

Misc.

  • Hardcoding the string value directly into setText()
  • Various combinations of all of the above
  • removing android:clickable="false"
  • removing android:cursorVisible="false"
  • removing android:focusable="false"
  • removing android:focusableInTouchMode="false"

Code snippet:

// Message passed to next activity via putExtra()
message = "This\n Is\n A Test";
// Next Activity
TextView messageTextView = (TextView) findViewById(R.id.messageToUser);
String message = getIntent().getStringExtra("message");
messageTextView.setText(message);

Current and Updated XML for the TextView:

<TextView
    android:id="@+id/messageToUser"
    android:layout_width="0dp"
    android:layout_height="200dp"
    android:background="#90FFFFFF"
    android:ems="10"
    android:fontFamily="serif"
    android:text=""
    android:textAlignment="center"
    android:textColor="@android:color/black"
    android:textSize="30sp"
    android:textStyle="bold"
    tools:layout_constraintTop_creator="1"
    tools:layout_constraintRight_creator="1"
    android:layout_marginStart="165dp"
    android:layout_marginEnd="165dp"
    app:layout_constraintRight_toRightOf="parent"
    android:layout_marginTop="209dp"
    tools:layout_constraintLeft_creator="1"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintTop_toTopOf="parent" />

If this helps, I'm on Windows 7, Android Studio 2.3.2, Java 1.8, designing an App Specifically for SM-T580 (Samsung Tab A 10.1"), the TextView's parent is the base ConstraintLayout of the component tree

like image 813
pianoisland Avatar asked Jun 15 '17 04:06

pianoisland


1 Answers

try this \n corresponds to ASCII char 0xA, which is 'LF' or line feed

        tv.setText("First line " + System.getProperty("line.separator") + "Line 2"+ System.getProperty("line.separator") + "Line 3");


String String1 = "value 1";
String String2 = "value 2";
TextView.setText(String1 + "\n" + String2);

or try this

string = string.replace("\\\n", System.getProperty("line.separator"));

for hardcore string try this

<string name="value"> This\nis a sample string data</string>

or

<string name="value> This<br>is a sample<br> String data</string>
like image 180
AskNilesh Avatar answered Oct 02 '22 19:10

AskNilesh