Подтвердить что ты не робот

Как создать пользовательский макет уведомлений в android?

как показать полный контент в уведомлении в frist time в android с использованием стиля уведомлений или для перехода на пользовательский макет

4b9b3361

Ответ 1

Я использовал BitTextStyle() для добавления выделенного текста в уведомление.

return new NotificationCompat.Builder(context)
       .setSmallIcon(R.drawable.ic_mono)
       .setContentTitle(title)
       .setContentText(message)
       .setLargeIcon(icon)
       .setColor(ContextCompat.getColor(context, R.color.notification_color))
       .setStyle(new NotificationCompat.BigTextStyle().bigText(title))
       .setStyle(new NotificationCompat.BigTextStyle().bigText(message).setSummaryText("#hashtag"))
       .setShowWhen(true)
       .setAutoCancel(true);

Ответ 2

Используйте собственный contentView в своем конструкторе уведомлений

Чтобы определить настраиваемый макет уведомлений, начните с создания экземпляра RemoteViews, который раздувает файл макета XML. Тогда вместо вызывающие методы, такие как setContentTitle(), вызов setContent(). Устанавливать сведения о контенте в пользовательском уведомлении, используйте методы в RemoteViews, чтобы установить значения дочерних элементов вида:

Создайте XML-макет для уведомления в отдельном файле. Вы может использовать любое имя файла, которое вы хотите, но вы должны использовать расширение .xml     В своем приложении используйте методы RemoteViews для определения значков уведомлений и текста. Поместите этот объект RemoteViews в свой NotificationCompat.Builder, вызывая setContent(). Избегайте background Подходит для вашего объекта RemoteViews, потому что ваш текст цвет может стать нечитаемым.

custom_push.xml имеет мои пользовательские представления R.id.image, R.id.text, R.id.title

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/layout"
    android:layout_width="fill_parent"
    android:layout_height="64dp"
    android:padding="10dp" >
    <ImageView
        android:src="@mipmap/ic_launcher"
        android:id="@+id/image"
        android:layout_width="wrap_content"
        android:layout_height="fill_parent"
        android:layout_alignParentLeft="true"
        android:layout_marginRight="10dp" />
    <TextView
        android:textSize="13dp"
        android:textColor="#000"
        android:text="Testing"
        android:id="@+id/title"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_toRightOf="@id/image"
        />
    <TextView
        android:textSize="13dp"
        android:textColor="#000"
        android:text="Testing is awecome"
        android:id="@+id/text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_toRightOf="@id/image"
        android:layout_below="@id/title"
         />
</RelativeLayout>

Создавая объект RemoteViews и устанавливая его,

RemoteViews contentView = new RemoteViews(getPackageName(), R.layout.custom_push);
contentView.setImageViewResource(R.id.image, R.mipmap.ic_launcher);
contentView.setTextViewText(R.id.title, "Custom notification");
contentView.setTextViewText(R.id.text, "This is a custom layout");

NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.icon)
.setContent(contentView);

Notification notification = mBuilder.build();
notification.flags |= Notification.FLAG_AUTO_CANCEL;
notification.defaults |= Notification.DEFAULT_SOUND;
notification.defaults |= Notification.DEFAULT_VIBRATE;
notificationManager.notify(1, notification);

введите описание изображения здесь

check: https://developer.android.com/guide/topics/ui/notifiers/notifications.html#ApplyStyle

Ответ 3

Я предполагаю, что вы ищете .setSubText(). Уведомление о флипкарте, которое вы указали, определенно не является обычным представлением.

NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
                        .setSmallIcon(icon)
                        .setSubText("Limited Stocks, Don't Wait!") <-------
                        .setContentTitle("Custom Notification Title")
notificationBuilder.notify(1, notificationBuilder.build());

Ответ 4

Этот код работал для меня.

    private static RemoteViews contentView;
    private static Notification notification;
    private static NotificationManager notificationManager;
    private static final int NotificationID = 1005;
    private static NotificationCompat.Builder mBuilder;

    private void RunNotification() {

        notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        mBuilder = new NotificationCompat.Builder(getApplicationContext(), "notify_001");

        contentView = new RemoteViews(getPackageName(), R.layout.my_notification_layout);
        contentView.setImageViewResource(R.id.image, R.mipmap.ic_launcher);
        Intent switchIntent = new Intent(this, BackgroundService.switchButtonListener.class);
        PendingIntent pendingSwitchIntent = PendingIntent.getBroadcast(this, 1020, switchIntent, 0);
        contentView.setOnClickPendingIntent(R.id.flashButton, pendingSwitchIntent);

        mBuilder.setSmallIcon(R.mipmap.newicon);
        mBuilder.setAutoCancel(false);
        mBuilder.setOngoing(true);
        mBuilder.setPriority(Notification.PRIORITY_HIGH);
        mBuilder.setOnlyAlertOnce(true);
        mBuilder.build().flags = Notification.FLAG_NO_CLEAR | Notification.PRIORITY_HIGH;
        mBuilder.setContent(contentView);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            String channelId = "channel_id";
            NotificationChannel channel = new NotificationChannel(channelId, "channel name", NotificationManager.IMPORTANCE_HIGH);
            channel.enableVibration(true);
            channel.setVibrationPattern(new long[]{100, 200, 300, 400, 500, 400, 300, 200, 400});
            notificationManager.createNotificationChannel(channel);
            mBuilder.setChannelId(channelId);
        }

        notification = mBuilder.build();
        notificationManager.notify(NotificationID, notification);
    }

это мой макет уведомления

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="50dp"
    android:background="#e9ebe9">

    <ImageView
        android:id="@+id/flashButton"
        android:layout_width="180dp"
        android:layout_height="50dp"
        android:layout_alignParentRight="true"
        android:layout_centerVertical="true"
        android:layout_marginRight="-20dp"
        android:src="@drawable/turnoff2" />

    <ImageView
        android:layout_width="100dp"
        android:layout_height="45dp"
        android:layout_alignParentLeft="true"
        android:layout_marginLeft="-10dp"
        android:layout_marginTop="5dp"
        android:layout_marginBottom="5dp"
        android:src="@mipmap/newicon" />

    <RelativeLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerVertical="true"
        android:layout_marginLeft="80dp">

        <TextView
            android:id="@+id/title"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentLeft="true"
            android:text="Flashlight"
            android:textColor="#000000"
            android:textSize="13sp" />

        <TextView
            android:id="@+id/charging"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_below="@+id/title"
            android:layout_alignParentLeft="true"
            android:layout_marginTop="3dp"
            android:text="90% Charging"
            android:textColor="#000000"
            android:textSize="13sp" />
    </RelativeLayout>

</RelativeLayout>

Я надеюсь, что это может помочь вам