当前位置: 移动技术网 > IT编程>移动开发>Android > Notification自定义界面

Notification自定义界面

2019年07月24日  | 移动技术网IT编程  | 我要评论

李修蒙,电子技术论坛,你的名字1080

前言

之前在做一个手机的播放器,需要做到在通知栏显示控制播放的界面,如下:

这里写图片描述

这是让服务在前台运行就可以实现的(可以参考我的前一篇文章service在前台运行),今天我们就要实现notification的自定义界面,当然就不实现如上图所示的了,而是下面一个简单的界面,随自己的需要搭建自己想要的界面。

这里写图片描述

可以看到,我实现了一个简单的界面,包括一个imageview和button,下面我就说说该如何实现它,其实很简单。

实现

首先我们要准备一个界面文件:

notification.xml

<?xml version="1.0" encoding="utf-8"?>
<linearlayout xmlns:android="http://schemas.android.com/apk/res/android"
 android:layout_margintop="10dp"
 android:layout_marginbottom="10dp"
 android:background="#333300"
 android:layout_width="match_parent"
 android:layout_height="match_parent">
 <imageview
  android:paddingleft="20dp"
  android:layout_width="70dp"
  android:layout_height="50dp"
  android:src="@drawable/ic_qiuda"
  />
 <button
  android:layout_marginleft="30dp"
  android:layout_width="wrap_content"
  android:layout_height="wrap_content"
  android:text="点击我"
  />
</linearlayout>

然后新建一个service的子类,myservice:

public class myservice extends service {

 public static final string tag = "myservice";

 @override
 public void oncreate() {
  super.oncreate();
  notification notification = new notification(r.drawable.ic_launcher,
    "jcman", system.currenttimemillis());
  remoteviews view = new remoteviews(getpackagename(),r.layout.notification);
  notification.contentview = view;
  startforeground(1, notification);

 }
 @override
 public ibinder onbind(intent intent) {
  return null;
 }
}

可以看到,在oncreate方法里面我们设置界面的不再是用layoutinflater来得到界面,而是用remoteviews来new出来一个界面,构造方法传入的是包名和界面资源的id即可,然后我们把notification.contentview设置成我们new出来的自定义界面即可。

小结

普通的notification可以用来进行通知,但是当有特殊需要的时候,我们就需要自定义界面,而且有时候还需要对自定义的界面添加点击的方法,如在上图的界面里面有一个button如何对button的点击事件进行响应,这是一个比较难的问题,因为这不是简单的setonclicklistener就可以的,需要另外的实现,需要用到广播机制,我将会在下一篇文章中说明如何为notification的自定义界面添加点击事件。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网