Giới thiệu
Thread có tên có thể đặt và lấy. Ví dụ này tạo thread mới, đặt tên từ EditText, sau 500ms hiển thị tên thread lên TextView.
Bước 1: Tạo project 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">
<EditText android:id="@+id/edit_query" android:layout_width="match_parent"
android:layout_height="wrap_content" android:hint="Nhập tên thread" />
<Button android:id="@+id/click" android:layout_marginTop="50dp"
android:layout_width="wrap_content" android:layout_height="wrap_content"
android:background="#c1c1c1" android:textColor="#FFF" android:text="Tạo Thread" />
<TextView android:id="@+id/text" android:layout_width="wrap_content" android:layout_height="wrap_content" />
</LinearLayout>
Bước 3: MainActivity.java
package com.example.myapplication;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
EditText edit_query;
TextView textView;
Thread t;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
edit_query = findViewById(R.id.edit_query);
textView = findViewById(R.id.text);
findViewById(R.id.click).setOnClickListener(v -> runThread());
}
private void runThread() {
final String threadName = edit_query.getText().toString();
if (threadName.isEmpty()) return;
t = new Thread(() -> {
try {
Thread.sleep(500); // Giả lập công việc nền
} catch (InterruptedException e) {
e.printStackTrace();
}
// Cập nhật UI trên main thread
runOnUiThread(() -> textView.setText("Tên thread: " + t.getName()));
});
t.setName(threadName); // Đặt tên
t.start();
}
}
Chạy ứng dụng
Nhập tên, nhấn nút. Sau 0.5 giây TextView hiển thị tên thread vừa đặt.
