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

Cách tải lại (reload) Activity trong Android

Giới thiệu

Trong một số trường hợp, chúng ta cần khởi động lại Activity từ phương thức onCreate(). Ví dụ này minh họa cách reload Activity trong Android.

Bước 1: Tạo dự án mới

Android Studio → File → New Project → Hoàn tất.

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"
    android:id="@+id/parent"
    xmlns:tools="https://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity"
    android:gravity="center"
    android:orientation="vertical">

    <TextView
        android:id="@+id/text"
        android:textSize="28sp"
        android:textAlignment="center"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

</LinearLayout>

Bước 3: Logic reload (src/MainActivity.java)

package com.example.andy.myapplication;

import android.content.Intent;
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.TextView;

public class MainActivity extends AppCompatActivity {
    int view = R.layout.activity_main;
    TextView textview;

    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(view);

        textview = findViewById(R.id.text);
        textview.setText("Nhấn vào đây để tải lại Activity");
        textview.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MainActivity.this, MainActivity.class);
                finish();
                overridePendingTransition(0, 0);
                startActivity(intent);
                overridePendingTransition(0, 0);
            }
        });
    }
}

Giải thích mã quan trọng

Intent intent = new Intent(MainActivity.this, MainActivity.class);
finish();
overridePendingTransition(0, 0);
startActivity(intent);
overridePendingTransition(0, 0);
  • Intent(MainActivity.this, MainActivity.class): Tạo Intent trỏ đến chính Activity hiện tại
  • finish(): Kết thúc Activity hiện tại (gọi onDestroy)
  • overridePendingTransition(0, 0): Tắt animation chuyển cảnh (trước và sau startActivity) để reload mượt mà
  • startActivity(intent): Khởi động Activity mới (gọi onCreate lại)

Chạy ứng dụng

Chạy app → Màn hình hiển thị TextView. Nhấn vào TextView → Activity được reload hoàn toàn (onCreate chạy lại), giao diện reset về trạng thái ban đầu.

Cách thay thế hiện đại (API 11+)

Từ API 11, có thể dùng recreate() đơn giản hơn:

textview.setOnClickListener(v -> recreate());