Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Android

Cách dùng StringWriter append trong Android

Sử dụng StringWriter.append() trong Android

Ví dụ minh họa sử dụng java.io.StringWriter để xây dựng chuỗi hiệu quả (nối chuỗi) và hiển thị lên TextView khi nhấn nút.

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="30dp"
    tools:context=".MainActivity">

    <EditText
        android:id="@+id/edit_query"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="Nhập văn bản..." />

    <Button
        android:id="@+id/buttonPanel"
        android:text="Append với StringWriter"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

    <TextView
        android:id="@+id/text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="18sp"
        android:layout_marginTop="20dp" />

</LinearLayout>

Bước 3: Code logic (src/MainActivity.java)

package com.example.myapplication;

import android.os.Build;
import android.os.Bundle;
import android.support.annotation.RequiresApi;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import java.io.StringWriter;

public class MainActivity extends AppCompatActivity {

    TextView text;
    EditText edit_query;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        edit_query = findViewById(R.id.edit_query);
        text = findViewById(R.id.text);

        findViewById(R.id.buttonPanel).setOnClickListener(new View.OnClickListener() {
            @RequiresApi(api = Build.VERSION_CODES.KITKAT) // StringWriter.append(CharSequence) từ API 19
            @Override
            public void onClick(View v) {
                String input = edit_query.getText().toString();
                if (!input.isEmpty()) {
                    StringWriter sw = new StringWriter();
                    sw.append("String Writer: ");
                    sw.append(input);
                    // sw.append('\n'); // Có thể append char
                    text.setText(sw.toString());
                }
            }
        });
    }
}

Tại sao dùng StringWriter?

  • Hiệu quả hơn String concatenation (+) khi nối nhiều lần (tránh tạo nhiều object rác).
  • Implement Appendable, Closeable, Flushable.
  • Tự động mở rộng buffer (mặc định 16 chars).
  • Thread-safe (các phương thức synchronized).

So sánh hiệu năng

// Kém hiệu quả (tạo nhiều String object trung gian)
String s = "";
for (int i = 0; i < 1000; i++) s += "a";

// Tốt: StringBuilder (non-sync, nhanh nhất cho single-thread)
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 1000; i++) sb.append("a");

// Tốt: StringWriter (khi cần Writer interface, ví dụ ghi vào stream)
StringWriter sw = new StringWriter();
for (int i = 0; i < 1000; i++) sw.append("a");

Lưu ý

Trong Android, StringBuilder thường ưu tiên hơn StringWriter cho việc nối chuỗi đơn thuần do nhẹ hơn và không synchronized. StringWriter hữu ích khi cần tuân thủ interface Writer (ví dụ: truyền cho thư viện JSON/XML serializer).

Chạy ứng dụng

Nhập text → nhấn nút → TextView hiển thị: String Writer: [nội dung nhập].

Cách dùng StringWriter append trong Android