Đếm số Paragraph trong TextView Android
Ví dụ này minh họa cách đếm số đoạn văn bản (paragraph) trong TextView bằng cách tách chuỗi theo ký tự xuống dòng kép (\\r\\n\\r\\n).
Bước 1: Tạo dự án mới
Android Studio → File → New Project.
Bước 2: Giao diện (res/layout/activity_main.xml)
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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"
android:orientation="vertical"
android:gravity="center_horizontal"
android:layout_marginTop="100dp"
tools:context=".MainActivity">
<TextView
android:id="@+id/text"
android:gravity="center"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
Bước 3: Code logic (src/MainActivity.java)
package com.example.myapplication;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
TextView text;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
text = findViewById(R.id.text);
// Văn bản có nhiều đoạn (phân cách bằng dòng trống)
String multiParagraph = "Lorem Ipsum is simply dummy text of the printing and typesetting industry.\n\n" +
"Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, " +
"when an unknown printer took a galley of type and scrambled it to make a type specimen book.\n\n" +
"It has survived not only five centuries, but also the leap into electronic typesetting, " +
"remaining essentially unchanged.\n\n" +
"It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, " +
"and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.";
text.setText(multiParagraph);
// Tách đoạn văn bằng \\r\\n\\r\\n (Windows) hoặc \\n\\n (Unix/Linux/Android)
String[] paragraphs = text.getText().toString().split("\\r?\\n\\r?\\n");
Toast.makeText(MainActivity.this, "Số đoạn văn: " + paragraphs.length, Toast.LENGTH_LONG).show();
}
}
Lưu ý về ký tự xuống dòng
- Windows:
\\r\\n(CRLF) - Unix/Linux/Android:
\\n(LF) - Regex
\\r?\\n\\r?\\nxử lý được cả hai trường hợp.
Cải tiến: Xử lý đoạn văn thực tế
// Tách theo bất kỳ chuỗi xuống dòng kép nào
String[] paras = text.getText().toString()
.split("(\\r\\n|\\r|\\n){2,}");
// Hoặc dùng Pattern để linh hoạt hơn
Pattern p = Pattern.compile("\\n\\s*\\n");
String[] paras = p.split(text.getText().toString());
Chạy ứng dụng
Toast hiển thị số đoạn văn (ví dụ: 4 đoạn với văn bản mẫu).
