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

Cách mở Activity mới khi nhấn Button trong Android?

Giới thiệu

Bài viết minh họa cách chuyển màn hình (start new Activity) khi người dùng nhấn Button, sử dụng Intent explicit.

Các bước thực hiện

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

Khởi tạo project Android Studio.

Bước 2: MainActivity với Button (res/layout/activity_main.xml)

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:text="Mở Activity mới!"
        android:textSize="32dp"
        android:textColor="@color/colorPrimary"
        android:textStyle="bold"/>
</RelativeLayout>

Bước 3: MainActivity xử lý click (src/MainActivity.java)

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

public class MainActivity extends AppCompatActivity {
    Button button;

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

        button = findViewById(R.id.button);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                openNewActivity();
            }
        });
    }

    public void openNewActivity() {
        Intent intent = new Intent(this, NewActivity.class);
        startActivity(intent);
    }
}

Bước 4: Layout Activity thứ 2 (res/layout/activity_second.xml)

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:padding="10dp"
        android:text="Chào mừng đến Activity mới"
        android:textColor="@color/colorPrimaryDark"
        android:textSize="32dp"/>
</RelativeLayout>

Bước 5: SecondActivity (src/NewActivity.java)

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

public class NewActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_new);
    }
}

Bước 6: Đăng ký Activity trong AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android"
    package="app.com.sample">
    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".NewActivity"></activity>
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
</manifest>

Chạy ứng dụng

Kết nối thiết bị, nhấn Run. Nhấn Button "Mở Activity mới!" → chuyển sang NewActivity hiển thị dòng chữ chào mừng.

Cách mở Activity mới khi nhấn Button trong Android?

Cách mở Activity mới khi nhấn Button trong Android?

Kiến thức mở rộng

1. Truyền dữ liệu qua Intent

// Gửi
Intent intent = new Intent(this, NewActivity.class);
intent.putExtra("key_name", "Giá trị String");
intent.putExtra("key_age", 25);
intent.putExtra("key_score", 99.5f);
startActivity(intent);

// Nhận
String name = getIntent().getStringExtra("key_name");
int age = getIntent().getIntExtra("key_age", 0); // default 0
float score = getIntent().getFloatExtra("key_score", 0f);

2. Nhận kết quả trả về (startActivityForResult - deprecated API 30+)

// Cũ (deprecated)
startActivityForResult(intent, REQUEST_CODE);

// Mới (Activity Result API - AndroidX)
ActivityResultLauncher<Intent> launcher = registerForActivityResult(
    new ActivityResultContracts.StartActivityForResult(),
    result -> {
        if (result.getResultCode() == RESULT_OK) {
            Intent data = result.getData();
            // Xử lý data
        }
    }
);
launcher.launch(intent);

3. Intent Implicit (mở app khác)

// Mở trang web
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("https://google.com"));
startActivity(intent);

// Gọi điện
Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:0123456789"));
startActivity(intent);

4. Flags thường dùng

  • FLAG_ACTIVITY_NEW_TASK: Mở trong task mới
  • FLAG_ACTIVITY_CLEAR_TOP: Xóa các Activity trên stack nếu đã tồn tại
  • FLAG_ACTIVITY_SINGLE_TOP: Không tạo mới nếu đã ở top
  • FLAG_ACTIVITY_NO_HISTORY: Không lưu vào back stack