Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Android

วิธีเปลี่ยนสีพื้นหลังและข้อความวิ่งใน Android Notification

ภาพรวม

ตัวอย่างนี้สาธิตการสร้าง Custom Notification Layout ด้วย RemoteViews เพื่อกำหนดสีพื้นหลัง การจัดวาง และข้อความวิ่ง (Marquee) เอง

ขั้นตอนที่ 1: สร้างโปรเจกต์

Android Studio → File → New Project

ขั้นตอนที่ 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="Create Custom Notification" />

</RelativeLayout>

ขั้นตอนที่ 3: Custom Notification Layout (res/layout/custom_notification_layout.xml)

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="https://schemas.android.com/apk/res/android"
    android:id="@+id/layout"
    android:layout_width="match_parent"
    android:layout_height="64dp"
    android:background="@color/colorAccent"
    android:padding="10dp">

    <ImageView
        android:id="@+id/image"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_alignParentStart="true"
        android:layout_marginEnd="10dp"
        android:contentDescription="@string/app_name"
        android:src="@mipmap/ic_launcher" />

    <TextView
        android:id="@+id/title"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_toEndOf="@id/image"
        android:text="Custom Title"
        android:textColor="#000"
        android:textSize="13sp" />

    <TextView
        android:id="@+id/text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/title"
        android:layout_toEndOf="@id/image"
        android:ellipsize="marquee"
        android:singleLine="true"
        android:text="Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s..."
        android:textColor="#000"
        android:textSize="13sp"
        android:focusable="true"
        android:focusableInTouchMode="true"
        android:marqueeRepeatLimit="marquee_forever" />

</RelativeLayout>

ขั้นตอนที่ 4: MainActivity.java

package app.tutorialspoint.com.notifyme;

import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.os.Bundle;
import android.view.View;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.NotificationCompat;
import android.widget.RemoteViews;

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) {
        // สร้าง RemoteViews จาก Custom Layout
        RemoteViews contentView = new RemoteViews(getPackageName(), R.layout.custom_notification_layout);
        
        // สามารถตั้งค่า Text ดินามิกได้
        contentView.setTextViewText(R.id.title, "Custom Notification");
        contentView.setTextViewText(R.id.text, "ข้อความวิ่งทดสอบ: การแจ้งเตือนแบบกำหนดเอง สีพื้นหลัง สามารถปรับแต่งได้เต็มที่");

        NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        NotificationCompat.Builder builder = new NotificationCompat.Builder(this, default_notification_channel_id)
                .setCustomContentView(contentView)  // ใช้ Custom Layout
                .setSmallIcon(R.drawable.ic_launcher_foreground)
                .setAutoCancel(true);

        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
            int importance = NotificationManager.IMPORTANCE_HIGH;
            NotificationChannel channel = new NotificationChannel(
                    NOTIFICATION_CHANNEL_ID, "Custom Notifications", importance);
            builder.setChannelId(NOTIFICATION_CHANNEL_ID);
            manager.createNotificationChannel(channel);
        }

        manager.notify((int) System.currentTimeMillis(), builder.build());
    }
}

ขั้นตอนที่ 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>

คำอธิบายสำคัญ

  • RemoteViews: ใช้สร้าง UI ใน Process อื่น (System UI) รองรับ View พื้นฐานเท่านั้น
  • setCustomContentView(): แทนที่ Content View ปกติของ Notification
  • Marquee (ข้อความวิ่ง): ต้องตั้งค่า ellipsize="marquee", singleLine="true", focusable="true", focusableInTouchMode="true"
  • สีพื้นหลัง: กำหนดใน Layout XML (android:background) หรือ contentView.setInt(R.id.layout, "setBackgroundColor", color)

ข้อจำกัดของ Custom Notification

  • ไม่รองรับ View ทุกชนิด (ไม่มี WebView, VideoView, RecyclerView)
  • ขนาดสูงสุดประมาณ 256dp (Expanded View)
  • ต้องทดสอบบนหลาย OEM (Samsung, Xiaomi, OnePlus) เพราะ UI Notification แตกต่างกัน
  • Android 12+ (API 31) แนะนำให้ใช้ NotificationCompat.DecoratedCustomViewStyle แทน

รูปแบบ Modern (API 31+)

NotificationCompat.Builder builder = new NotificationCompat.Builder(this, CHANNEL_ID)
        .setCustomContentView(contentView)
        .setCustomBigContentView(expandedView)  // สำหรับขยาย
        .setStyle(new NotificationCompat.DecoratedCustomViewStyle())
        .setSmallIcon(R.drawable.ic_launcher_foreground);