和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就做好了:
本文介绍如何使用RemoteViews类来自定义Notification的样式,包括如何实例化RemoteViews、设置控件属性及监听器,最后将其应用于Notification中。
1190

被折叠的 条评论
为什么被折叠?



