在android项目的开发中,有时为了实现和用户更好的交互,在通知栏这一小小的旮旯里,我们通常需要将内容丰富起来,这个时候我们就需要去实现自定义的通知栏,例如下面360或者网易的样式:
首先我们要了解的是 自定义布局文件支持的控件类型:Notification的自定义布局是RemoteViews,因此,它仅支持FrameLayout、LinearLayout、RelativeLayout三种布局控件,同时支持AnalogClock、Chronometer、Button、ImageButton、ImageView、ProgressBar、TextView、ViewFlipper、ListView、GridView、StackView和AdapterViewFlipper这些UI控件。对于其他不支持的控件,使用时将会抛出ClassNotFoundException异常。
同时呢我们还要了解的是Notification支持的Intent类型(都是PendingIntent类的实例)。
下面就是具体的实现了:在这个通知栏里 我们放一个进度条
//Get the notification manager
String ns = Context.NOTIFICATION_SERVICE;
NotificationManager nm =
(NotificationManager)ctx.getSystemService(ns);
//Create Notification Object
int icon = R.drawable.robot;
CharSequence tickerText = "Hello";
long when = System.currentTimeMillis();
Notification notification =
new Notification(icon, tickerText, when);
//Set ContentView using setLatestEvenInfo
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse("http://www.google.com"));
PendingIntent pi = PendingIntent.getActivity(ctx, 0, intent, 0);
// notification.setLatestEventInfo(ctx, "title", "text", pi);// 使用默认的样式
notification.contentIntent = pi;
notification.contentView = new RemoteViews(ctx.getPackageName(),R.layout.noti);
//Send notification
nm.notify(1, notification);
实现的效果如下图:(右边为系统默认的样式)
这只是一个简单的示例,为了实现我们自己的效果 我们只需要修改布局文件就ok了。