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

Triển khai thu gọn/mở rộng thông báo Android (Expand/Collapse)

Giới thiệu

Ví dụ này minh họa cơ chế Expand (mở rộng) và Collapse (thu gọn) của thông báo Android. Sử dụng BigTextStyle để cho phép người dùng vuốt để xem thêm nội dung.

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

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

Tạo project Android Studio mới.

Bước 2: Layout (res/layout/activity_main.xml)

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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"
    tools:context=".MainActivity">

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:layout_margin="16dp"
        android:onClick="createNotification"
        android:text="Tạo thông báo Expand/Collapse" />

</RelativeLayout>

Bước 3: strings.xml (res/values/strings.xml)

<resources>
    <string name="app_name">NotifyMe</string>
    <string name="lorem_ipsum">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium.</string>
</resources>

Bước 4: MainActivity (src/MainActivity.java)

package app.tutorialspoint.com.notifyme;

import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.NotificationCompat;
import android.support.v7.app.AppCompatActivity;
import android.view.View;

public class MainActivity extends AppCompatActivity {
    public static final String NOTIFICATION_CHANNEL_ID = "10001";
    private final static String default_notification_channel_id = "default";

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

    public void createNotification(View view) {
        NotificationManager mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(
            MainActivity.this, default_notification_channel_id);

        String longText = getResources().getString(R.string.lorem_ipsum);

        mBuilder.setContentTitle("Thông báo Expand/Collapse");
        mBuilder.setContentText(longText); // Dạng thu gọn
        
        // BẬT CHẾ ĐỘ MỞ RỘNG VỚI BIGTEXTSTYLE
        mBuilder.setStyle(new NotificationCompat.BigTextStyle()
            .bigText(longText)
            .setBigContentTitle("Nội dung chi tiết")
            .setSummaryText("Vuốt lên để thu gọn"));

        mBuilder.setSmallIcon(R.drawable.ic_launcher_foreground);
        mBuilder.setAutoCancel(true);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            int importance = NotificationManager.IMPORTANCE_HIGH;
            NotificationChannel notificationChannel = new NotificationChannel(
                NOTIFICATION_CHANNEL_ID, "Kênh Expand/Collapse", importance);
            mBuilder.setChannelId(NOTIFICATION_CHANNEL_ID);
            assert mNotificationManager != null;
            mNotificationManager.createNotificationChannel(notificationChannel);
        }

        assert mNotificationManager != null;
        mNotificationManager.notify((int) System.currentTimeMillis(), mBuilder.build());
    }
}

Bước 5: AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android"
    package="app.tutorialspoint.com.notifyme">

    <uses-permission android:name="android.permission.VIBRATE" />

    <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=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

    </application>
</manifest>

Cơ chế Expand/Collapse

Trạng thái Collapse (Thu gọn - mặc định)

  • Chiều cao cố định ~64-96dp
  • Hiển thị: Small icon, Title, 1-2 dòng ContentText, Time
  • Mũi tên chỉ xuống (nếu có style mở rộng)

Trạng thái Expand (Mở rộng)

  • Chiều cao tối đa ~256dp (tùy thiết bị)
  • Hiển thị: Toàn bộ bigText, BigContentTitle, SummaryText
  • User vuốt xuống (two-finger swipe down) hoặc nhấn mũi tên
  • Mũi tên chỉ lên

Các Style hỗ trợ Expand/Collapse

Style Dùng cho Phương thức chính
BigTextStyle Văn bản dài bigText()
InboxStyle Danh sách mục (email, tin nhắn) addLine()
BigPictureStyle Hình ảnh lớn bigPicture(bitmap)
MessagingStyle Cuộc hội thoại chat addMessage()
MediaStyle Phát nhạc/video setMediaSession()

Tự động mở rộng (Heads-up)

Để thông báo tự mở rộng ngay khi xuất hiện (heads-up notification):

// Trong Notification Channel
notificationChannel.setImportance(NotificationManager.IMPORTANCE_HIGH);
// Hoặc IMPORTANCE_MAX (Android 7.1-)

/* 
   Lưu ý: Heads-up chỉ hiện khi:
   - App đang chạy foreground
   - Importance HIGH/MAX
   - User không bật Do Not Disturb
*/

Chạy thử nghiệm

Chạy app → Tạo thông báo → Kéo thanh thông báo xuống → Thấy dạng thu gọn → Vuốt xuống thông báo bằng 2 ngón → Xem dạng mở rộng toàn văn bản → Vuốt lên để thu gọn lại.