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

Intent trong Android là gì?

Intent là đối tượng truyền ý định thực hiện hành động: khởi động Activity, gửi Broadcast, bắt đầu Service, truyền dữ liệu giữa các Activity.

Hai loại: Explicit Intent (chỉ định rõ component đích) và Implicit Intent (chỉ mô tả hành động, hệ thống tìm component phù hợp).

Ví dụ: Chuyển từ MainActivity sang SecondActivity

1. Layout MainActivity (button "Send to another activity"):

<Button android:id="@+id/send" android:text="Send to another activity" ... />

2. Layout SecondActivity (TextView hiển thị dữ liệu).

3. MainActivity.java:

Button send = findViewById(R.id.send);
send.setOnClickListener(v -> {
  Intent intent = new Intent(MainActivity.this, SecondActivity.class);
  startActivity(intent);
});

4. SecondActivity.java: setContentView, findViewById, setText.

5. AndroidManifest.xml khai báo cả hai Activity.

Chạy app, bấm button → mở SecondActivity.