Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Android

วิธีเพิ่มการขึ้นบรรทัดใหม่ใน TextView Android

ภาพรวม

ตัวอย่างนี้แสดงวิธีเพิ่มการขึ้นบรรทัดใหม่ (Line Break) ใน TextView ทั้งใน XML (strings.xml) และโค้ด Java

ขั้นตอนที่ 1: สร้างโปรเจกต์ใหม่

สร้างโปรเจกต์ Android ใหม่ใน Android Studio

ขั้นตอนที่ 2: จัดทำ Layout (activity_main.xml)

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:tools="https://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">
    <TextView
        android:id="@+id/textView"
        android:layout_centerInParent="true"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textSize="24sp"
        android:text="@string/Questions" />
</RelativeLayout>

ขั้นตอนที่ 3: MainActivity.java (ตั้งค่าสีข้อความ)

import android.graphics.Color;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {
    TextView textView;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        textView = findViewById(R.id.textView);
        textView.setTextColor(Color.RED);
    }
}

ขั้นตอนที่ 4: strings.xml - วิธีที่ 1 ใช้ <br> และ \n

<resources>
    <string name="app_name">Sample</string>
    <string name="Questions">
        <br />
        1. อาหารโปรดคืออะไร? \n
        <br />
        2. กีฬาโปรดคืออะไร?\n
        <br />
        3. Bucket list ของคุณคืออะไร?
        <br />
    </string>
</resources>

วิธีต่างๆ ในการขึ้นบรรทัดใหม่

วิธีรูปแบบใช้ในหมายเหตุ
Escape sequence\nJava Code / strings.xmlมาตรฐาน Java
HTML tag<br> 或 <br/>strings.xml / Html.fromHtml()ต้องใช้กับ setText(Html.fromHtml())
XML Entity&#10; 或 &#xA;strings.xmlLine Feed character
Kotlin\n หรือ \"\"\"multi-line\"\"\"Kotlin CodeRaw string รองรับหลายบรรทัด

การใช้ใน Java Code

// วิธี 1: ใช้ \n โดยตรง
textView.setText("บรรทัดแรก\nบรรทัดที่สอง\nบรรทัดที่สาม");

// วิธี 2: ใช้ Html.fromHtml (รองรับ <br>, <b>, <i>, <u>)
textView.setText(Html.fromHtml("บรรทัดแรก<br>บรรทัดที่สอง<br><b>หนา</b>"));

// วิธี 3: StringBuilder
StringBuilder sb = new StringBuilder();
for (String line : lines) {
    sb.append(line).append("\n");
}
textView.setText(sb.toString());

การใช้ใน XML Layout โดยตรง

<TextView
    android:text="บรรทัด 1\nบรรทัด 2\nบรรทัด 3"
    ... />

การทดสอบ

รันแอป จะแสดงข้อความ 3 บรรทัด ขึ้นบรรทัดใหม่ได้ถูกต้อง