#Android 自定义之Notification

本文介绍如何使用RemoteViews类来自定义Notification的样式,包括如何实例化RemoteViews、设置控件属性及监听器,最后将其应用于Notification中。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

和Toast一样,通知也可以使用自定义的XML来自定义样式,但是对于通知而言,因为它的全
局性,并不能简单的通过inflate膨胀出一个View,因为可能触发通知的时候,响应的App已
经关闭,无法获取当指定的XML布局文件。所以需要使用单独的一个RemoteViews类来操作
RemoteViews类
RemoteViews 类描述了一个View对象能够显示在其他进程中,可以融合从一个layout资源文
件实现布局。

这里写图片描述
如何实例化一个RemoteViews

RemoteViews(String packageName, int layoutId)
//通过指定的布局文件新建一个RemoteViews对象。
RemoteViews可以使用它的一系列setXxx()方法通过控件的Id设置控件的属性。
为控件设置监听1. public void setOnClickPendingIntent (int viewId, PendingIntent
pendingIntent)
//相当于调用View.OnClickListener启动准备好的PendingIntent。当在集合中设置
条目的onClick动作时不起作用。
//viewId 当点击时将要触发PendingIntent的视图的id
//pendingIntent 当点击时传过去的PendingIntent

最后使用Notification.Builder.setContent(RemoteViews)方法设置它到一个Notification
中。

Java代码:

  NotificationCompat.Builder builder=new NotificationCompat.Builder(this);
    builder.setSmallIcon(R.drawable.ic_launcher);
    builder.setContentTitle("@@@@@@");
    builder.setContentText("======");
    RemoteViews rViews=new RemoteViews(getPackageName(), R.layout.button);
    builder.setContent(rViews);
    Notification notification=builder.build();
    NotificationManager manager=(NotificationManager) getSystemService(NOTIFICATION_SERVICE);
    manager.notify(1, notification);

Xml布局:

      <ImageView 
    android:id="@+id/img"
    android:layout_width="80dp"
    android:layout_height="80dp"
    android:background="@drawable/m3"/>
 <ImageButton 
    android:layout_toRightOf="@id/img"
    android:id="@+id/img1"
    android:layout_width="60dp"
    android:layout_height="60dp"
    android:background="@drawable/m4"
    android:layout_marginTop="8dp"
    android:layout_marginLeft="10dp"/>

  <ImageButton
    android:layout_toRightOf="@id/img1"
    android:id="@+id/img2"
    android:layout_width="60dp"
    android:layout_height="60dp"
    android:background="@drawable/m2"
    android:layout_marginTop="8dp"
    android:layout_marginLeft="45dp"/>

   <ImageButton 
    android:layout_toRightOf="@id/img2"
    android:id="@+id/img3"
    android:layout_width="60dp"
    android:layout_height="60dp"
    android:background="@drawable/m1"
    android:layout_marginTop="8dp"
    android:layout_marginLeft="40dp"/>


 这样一个自定义的Notification就做好了:
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值