android Notification的自定义和实现通知栏的展开和收起

时间:2022-01-03 19:35:22

最近写项目遇到了这样一个问题,就是如何才能实现通知栏的伸展,效果直接上图android  Notification的自定义和实现通知栏的展开和收起

通知栏伸展后是

android  Notification的自定义和实现通知栏的展开和收起

其实实现这个效果还是比较简单的,但是查找了很多资料,大家都是说的马马虎虎,一样的模板,照抄照搬。

先来说一下如何实现Notification的自定义吧,这里需要设置的是Notification的ContentView,代码如下

remoteViews = new RemoteViews(getPackageName(),
R.layout.statusbar);
builder = new NotificationCompat.Builder(getApplicationContext());
        builder.setSmallIcon(R.drawable.ic_launcher)
.setOngoing(true)
.setTicker("music is playing");
notification=builder.build();
notification.contentView=remoteViews;

mNotificationManager.notify(1,notification);
这样就实现了自定义notification布局了。

现在讲一下如何设置notification伸展的布局,想上面一下

也很简单,只需要把RemoteView交付给bigContentView就可以了。

remoteViews_large=new RemoteViews(getPackageName(),R.layout.statusbar_1);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
notification.bigContentView=remoteViews_large;
}
因为Notification的bigContentView只有在SDK16以上才可以使用,所以这里应该做一个判断。

还有一点找那个要的是,在设置bigContentView和ContentView时,一定要先设置前再设置后者,不然会导致notification布局不显示。

现在上一下全部代码:

MainActivity:

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

private Button btn_start,btn_cancel;
private NotificationCompat.Builder builder;
private NotificationManager mNotificationManager;
private RemoteViews remoteViews,remoteViews_large;
private Notification notification;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initView();
}

private void initView() {
btn_start= (Button) findViewById(R.id.btn_start);
btn_cancel= (Button) findViewById(R.id.btn_cancel);
btn_start.setOnClickListener(this);
btn_cancel.setOnClickListener(this);
}

@Override
public void onClick(View v) {
switch (v.getId()){
case R.id.btn_start:
mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
remoteViews = new RemoteViews(getPackageName(),
R.layout.statusbar);
remoteViews_large=new RemoteViews(getPackageName(),R.layout.statusbar_1);

builder = new NotificationCompat.Builder(getApplicationContext());

builder.setSmallIcon(R.drawable.ic_launcher)
.setOngoing(true)
.setTicker("music is playing");
notification=builder.build();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
notification.bigContentView=remoteViews_large;
}
notification.contentView=remoteViews;

mNotificationManager.notify(1,notification);

break;
case R.id.btn_cancel:
mNotificationManager.cancel(1);

break;
}
}
}

看吧,其实就是这么简单。

示例下载:链接:http://pan.baidu.com/s/1c1Mw28C 密码:pp7j