Giới thiệu
Ví dụ này minh họa cách sử dụng phương thức getChars() để trích xuất một đoạn ký tự từ chuỗi trong EditText và hiển thị lên TextView.
Các bước thực hiện
Bước 1: Tạo dự án mới
Mở Android Studio, chọn File → New Project.
Bước 2: Thiết kế 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:app="https://schemas.android.com/apk/res-auto"
xmlns:tools="https://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:gravity="center"
tools:context=".MainActivity">
<EditText
android:id="@+id/name"
android:layout_width="match_parent"
android:hint="Nhập tên"
android:layout_height="wrap_content" />
<Button
android:id="@+id/click"
android:text="Nhấn"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:id="@+id/textview"
android:layout_width="wrap_content"
android:textSize="25sp"
android:layout_height="wrap_content" />
</LinearLayout>
Bước 3: Viết logic (src/MainActivity.java)
package com.example.myapplication;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
EditText name;
Button button;
TextView text;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
name = findViewById(R.id.name);
button = findViewById(R.id.click);
text = findViewById(R.id.textview);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String input = name.getText().toString();
if (!input.isEmpty()) {
// Trích xuất ký tự từ vị trí 9 đến hết chuỗi
char[] ch = new char[input.length() - 9];
input.getChars(9, input.length(), ch, 0);
text.setText(String.valueOf(ch));
} else {
name.setError("Vui lòng nhập tên");
}
}
});
}
}
Phương thức getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin) sao chép các ký tự từ vị trí srcBegin đến srcEnd-1 của chuỗi vào mảng ký tự dst bắt đầu từ dstBegin.
Chạy ứng dụng
Nhập chuỗi "tutorialspoint", kết quả sẽ hiển thị "point" (các ký tự từ vị trí 9 đến hết).
