详解Android中的沉浸式状态栏效果实例
无意间了解到沉浸式状态栏,感觉贼拉的高大上,于是就是试着去了解一下,就有了这篇文章。下面就来了解一下啥叫沉浸式状态栏。传统的手机状态栏是呈现出黑色条状的,有的和手机主界面有很明显的区别。这一样就在一定程度上牺牲了视觉宽度,界面面积变小。
google从android kitkat(android 4.4)开始,给我们开发者提供了一套能透明的系统ui样式给状态栏和导航栏,这样的话就不用向以前那样每天面对着黑乎乎的上下两条黑栏了,还可以调成跟activity一样的样式,形成一个完整的主题,和ios7.0以上系统一样了,沉浸式状态栏和主界面颜色和谐一体,视觉效果更加炫酷。
不过虽然听上去好像是很高大上的沉浸式效果,实际看上去貌似就是将内容全屏化了而已嘛。其实这算是一个争议点了。不少人纠结于沉浸式状态栏到底是将屏幕显示内容扩大还是仅仅是改变状态栏、标题栏的颜色。其实我更倾向于后者。在4.4之前状态栏一直是黑色的,在4.4中带来了 windowtranslucentstatus 这一特性,因此可以实现给状态栏设置颜色,视觉上的效果,感觉容器部分和状态栏、标题栏融为一体,更加直接的说就是改变状态栏、标题栏的颜色,当时可以根据界面颜色改变状态栏、标题栏的颜色实现跟加完整的界面显示,这应该是沉浸式状态栏受追捧的原因吧。
谷歌并没有给出沉浸式状态栏这个概念,谷歌只说了沉浸式模式(immersive mode)。不过沉浸式状态栏这个名字其实挺不错,只能随大众,但是android的环境并没有ios环境一样特别统一,比如华为rom的跟小米rom的虚拟按键完全不一样,并且安卓版本众多涉及到版本兼容问题,所有android开发者不容易。这点在沉浸式状态栏的开发中显得尤为重要。如果你在4.4之前的机子上显示沉浸式状态栏的话,经常出现一些意想不到的结果。
沉浸式是app界面图片延伸到状态栏, 应用本身沉浸于状态栏,所以如果第三方的软件没有为状态栏分配图片,那么自然就是黑色。顶端的状态栏和下面的虚拟按键都隐藏,需要的时候从边缘划出。沉浸模式。当启用该模式,应用程序的界面将占据整个屏幕,系统自动将隐藏系统的状态栏和导航栏,让应用程序内容可以在最大显示范围呈现,增加大屏体验,而当需要查看通知的时候只需要从顶部向下滑动就能呼出通知栏。
沉浸模式实际上有两种: 一种叫“沉浸模式”,状态栏和虚拟按钮会自动隐藏、应用自动全屏,这种模式下,应用占据屏幕的全部空间, 只有当用户从屏幕的上方边沿处向下划动时, 才会退出沉浸模式, 用户触摸屏幕其它部分时, 不会退出该模式, 这种模式比较适用于阅读器、 杂志类应用。另外一种叫“黏性沉浸模式”,让状态栏和虚拟按钮半透明,应用使用屏幕的全部空间, 当用户从屏幕的上方边沿处向下滑动时,也不会退出该模式, 但是系统界面 (状态栏、 导航栏) 将会以半透明的效果浮现在应用视图之上 , 只有当用户点击系统界面上的控件时, 才会退出黏性沉浸模式。
下面来说一说具体的实现。一个android应用程序的界面上其实是有很多系统元素的,有状态栏、actionbar、导航栏等。而打造沉浸式模式的用户体验,就是要将这些系统元素进行整合,当主界面改变时,状态栏、actionbar、导航栏同时也发生改变。这里先调用getwindow().getdecorview()方法获取到了当前界面的decorview,然后调用它的setsystemuivisibility()方法来设置系统ui元素的可见性。其中,system_ui_flag_fullscreen表示全屏的意思,也就是会将状态栏隐藏。另外,根据android的设计建议,actionbar是不应该独立于状态栏而单独显示的,因此状态栏如果隐藏了,我们同时也需要调用actionbar的hide()方法将actionbar也进行隐藏这种效果不叫沉浸式状态栏,也完全没有沉浸式状态栏这种说法,我们估且可以把它叫做透明状态栏效果吧。
隐藏状态栏:
setcontentview(r.layout.activity_main); //再该方法后执行 if (build.version.sdk_int >= 21) { view decorview = getwindow().getdecorview(); int option = view.system_ui_flag_layout_fullscreen | view.system_ui_flag_layout_stable; decorview.setsystemuivisibility(option); getwindow().setstatusbarcolor(color.transparent); } actionbar actionbar = getsupportactionbar(); actionbar.hide();
具体的沉浸效果该如何实现呢,系统提供实现沉浸式状态栏的方法,通过windowmanager来实现,可分为两步:
1. 在需要实现沉浸式状态栏的activity的布局中添加以下参数
android:fitssystemwindows="true" android:cliptopadding="true"
2. 在activity的setcontentview()方法后面调用初始化的方法即可。
private void initstate() { if (build.version.sdk_int >= build.version_codes.kitkat) { //透明状态栏 getwindow().addflags(windowmanager.layoutparams.flag_translucent_status); //透明导航栏 getwindow().addflags(windowmanager.layoutparams.flag_translucent_navigation); } }
当上述的实现效果,其实并不好, 没有在布局中设置cliptopadding为true的时候,会对应用的顶部toolbar进行拉伸,在布局中两个参数都进行设置后,顶部状态栏变成了白色。这样,我在github上找到一个很好的沉浸状态栏效果,来看一下。
首先添加依赖,导入下面的包。有时候可能会出现版本不统一的问题,依次保证联网的情况下点击一下同步android studio会自动下载包。
compile 'com.jaeger.statusbaruitl:library:1.2.5'
在自定义控件中实现的进本逻辑,代码较长。
package com.xiaoyuan; import android.content.context; import android.content.res.typedarray; import android.graphics.canvas; import android.graphics.drawable.drawable; import android.os.build; import android.util.attributeset; import android.view.motionevent; import android.view.view; import android.view.viewgroup; import android.view.animation.alphaanimation; import android.widget.scrollview; import java.util.arraylist; /** * @author emil sj�lander - sjolander.emil@gmail.com */ public class stickyscrollview extends scrollview { /** * tag for views that should stick and have constant drawing. e.g. * textviews, imageviews etc */ public static final string sticky_tag = "sticky"; /** * flag for views that should stick and have non-constant drawing. e.g. * buttons, progressbars etc */ public static final string flag_nonconstant = "-nonconstant"; /** * flag for views that have aren't fully opaque */ public static final string flag_hastransparancy = "-hastransparancy"; /** * default height of the shadow peeking out below the stuck view. */ private static final int default_shadow_height = 10; // dp; /** * xkj add for add 50dp offset of top */ private static int min_stick_top = 100;// px // private static final int min_stick_top = 0; private arraylist<view> stickyviews; private view currentlystickingview; private float stickyviewtopoffset; private int stickyviewleftoffset; private boolean redirecttouchestostickyview; private boolean clippingtopadding; private boolean cliptopaddinghasbeenset; private int mshadowheight; private drawable mshadowdrawable; private onscrollchangedlistener monscrollhandler = null; private ionscrolltoend monscrolltoend = null; private final runnable invalidaterunnable = new runnable() { @override public void run() { if (currentlystickingview != null) { int l = getleftforviewrelativeonlychild(currentlystickingview); int t = getbottomforviewrelativeonlychild(currentlystickingview); int r = getrightforviewrelativeonlychild(currentlystickingview); int b = (int) (getscrolly() + (currentlystickingview.getheight() + stickyviewtopoffset)); invalidate(l, t, r, b); } postdelayed(this, 16); } }; public stickyscrollview(context context) { this(context, null); } public stickyscrollview(context context, attributeset attrs) { this(context, attrs, android.r.attr.scrollviewstyle); } public stickyscrollview(context context, attributeset attrs, int defstyle) { super(context, attrs, defstyle); setup(); typedarray a = context.obtainstyledattributes(attrs, r.styleable.stickyscrollview, defstyle, 0); final float density = context.getresources().getdisplaymetrics().density; int defaultshadowheightinpix = (int) (default_shadow_height * density + 0.5f); mshadowheight = a.getdimensionpixelsize(r.styleable.stickyscrollview_stuckshadowheight, defaultshadowheightinpix); int shadowdrawableres = a.getresourceid(r.styleable.stickyscrollview_stuckshadowdrawable, -1); if (shadowdrawableres != -1) { mshadowdrawable = context.getresources().getdrawable(shadowdrawableres); } a.recycle(); } /** * sets the height of the shadow drawable in pixels. * * @param height */ public void setshadowheight(int height) { mshadowheight = height; } public void setup() { stickyviews = new arraylist<view>(); } private int getleftforviewrelativeonlychild(view v) { int left = v.getleft(); while (v.getparent() != getchildat(0)) { v = (view) v.getparent(); left += v.getleft(); } return left; } private int gettopforviewrelativeonlychild(view v) { int top = v.gettop(); while (v.getparent() != getchildat(0)) { v = (view) v.getparent(); top += v.gettop(); } return top; } private int getrightforviewrelativeonlychild(view v) { int right = v.getright(); while (v.getparent() != getchildat(0)) { v = (view) v.getparent(); right += v.getright(); } return right; } private int getbottomforviewrelativeonlychild(view v) { int bottom = v.getbottom(); while (v.getparent() != getchildat(0)) { v = (view) v.getparent(); bottom += v.getbottom(); } return bottom; } @override protected void onlayout(boolean changed, int l, int t, int r, int b) { super.onlayout(changed, l, t, r, b); if (!cliptopaddinghasbeenset) { clippingtopadding = true; } notifyhierarchychanged(); } @override public void setcliptopadding(boolean cliptopadding) { super.setcliptopadding(cliptopadding); clippingtopadding = cliptopadding; cliptopaddinghasbeenset = true; } @override public void addview(view child) { super.addview(child); findstickyviews(child); } @override public void addview(view child, int index) { super.addview(child, index); findstickyviews(child); } @override public void addview(view child, int index, android.view.viewgroup.layoutparams params) { super.addview(child, index, params); findstickyviews(child); } @override public void addview(view child, int width, int height) { super.addview(child, width, height); findstickyviews(child); } @override public void addview(view child, android.view.viewgroup.layoutparams params) { super.addview(child, params); findstickyviews(child); } @override protected void dispatchdraw(canvas canvas) { super.dispatchdraw(canvas); if (currentlystickingview != null) { canvas.save(); canvas.translate(getpaddingleft() + stickyviewleftoffset, getscrolly() + stickyviewtopoffset + (clippingtopadding ? getpaddingtop() : 0)); canvas.cliprect(0, (clippingtopadding ? -stickyviewtopoffset : 0), getwidth() - stickyviewleftoffset, currentlystickingview.getheight() + mshadowheight + 1); if (mshadowdrawable != null) { int left = 0; int right = currentlystickingview.getwidth(); int top = currentlystickingview.getheight(); int bottom = currentlystickingview.getheight() + mshadowheight; mshadowdrawable.setbounds(left, top, right, bottom); mshadowdrawable.draw(canvas); } canvas.cliprect(0, (clippingtopadding ? -stickyviewtopoffset : 0), getwidth(), currentlystickingview.getheight()); if (getstringtagforview(currentlystickingview).contains(flag_hastransparancy)) { showview(currentlystickingview); currentlystickingview.draw(canvas); hideview(currentlystickingview); } else { currentlystickingview.draw(canvas); } canvas.restore(); } } @override public boolean dispatchtouchevent(motionevent ev) { if (ev.getaction() == motionevent.action_down) { redirecttouchestostickyview = true; } if (redirecttouchestostickyview) { redirecttouchestostickyview = currentlystickingview != null; if (redirecttouchestostickyview) { redirecttouchestostickyview = ev.gety() <= (currentlystickingview.getheight() + stickyviewtopoffset) && ev.getx() >= getleftforviewrelativeonlychild(currentlystickingview) && ev.getx() <= getrightforviewrelativeonlychild(currentlystickingview); } } else if (currentlystickingview == null) { redirecttouchestostickyview = false; } if (redirecttouchestostickyview) { ev.offsetlocation(0, -1 * ((getscrolly() + stickyviewtopoffset) - gettopforviewrelativeonlychild(currentlystickingview))); // xkj add todo: remove this currentlystickingview.invalidate(); } return super.dispatchtouchevent(ev); } private boolean hasnotdoneactiondown = true; @override public boolean ontouchevent(motionevent ev) { if (redirecttouchestostickyview) { ev.offsetlocation(0, ((getscrolly() + stickyviewtopoffset) - gettopforviewrelativeonlychild(currentlystickingview))); } if (ev.getaction() == motionevent.action_down) { hasnotdoneactiondown = false; } if (hasnotdoneactiondown) { motionevent down = motionevent.obtain(ev); down.setaction(motionevent.action_down); super.ontouchevent(down); hasnotdoneactiondown = false; } if (ev.getaction() == motionevent.action_up || ev.getaction() == motionevent.action_cancel) { hasnotdoneactiondown = true; } return super.ontouchevent(ev); } @override protected void onscrollchanged(int l, int t, int oldl, int oldt) { super.onscrollchanged(l, t, oldl, oldt); dothestickything(); if (monscrollhandler != null) { monscrollhandler.onscrollchanged(l, t, oldl, oldt); } int maxscroll = getchildat(0).getheight() - getheight(); if (getchildcount() > 0 && t == maxscroll) { if (monscrolltoend != null) { monscrolltoend.onscrolltoend(); } } } public void setonscrolllistener(onscrollchangedlistener handler) { monscrollhandler = handler; } public interface onscrollchangedlistener { public void onscrollchanged(int l, int t, int oldl, int oldt); } public interface ionscrolltoend { public void onscrolltoend(); } public void setonscrolltoendlistener(ionscrolltoend handler) { monscrolltoend = handler; } private void dothestickything() { view viewthatshouldstick = null; view approachingview = null; for (view v : stickyviews) { int viewtop = gettopforviewrelativeonlychild(v) - getscrolly() + (clippingtopadding ? 0 : getpaddingtop()) - min_stick_top;// add 50dp if (viewtop <= 0) { if (viewthatshouldstick == null || viewtop > (gettopforviewrelativeonlychild(viewthatshouldstick) - getscrolly() + (clippingtopadding ? 0 : getpaddingtop()))) { viewthatshouldstick = v; } } else { if (approachingview == null || viewtop < (gettopforviewrelativeonlychild(approachingview) - getscrolly() + (clippingtopadding ? 0 : getpaddingtop()))) { approachingview = v; } } } if (viewthatshouldstick != null) { stickyviewtopoffset = approachingview == null ? min_stick_top : math.min(min_stick_top, gettopforviewrelativeonlychild(approachingview) - getscrolly() + (clippingtopadding ? 0 : getpaddingtop()) - viewthatshouldstick.getheight()); if (viewthatshouldstick != currentlystickingview) { if (currentlystickingview != null) { stopstickingcurrentlystickingview(); } // only compute the left offset when we start sticking. stickyviewleftoffset = getleftforviewrelativeonlychild(viewthatshouldstick); startstickingview(viewthatshouldstick); } } else if (currentlystickingview != null) { stopstickingcurrentlystickingview(); } } private void startstickingview(view viewthatshouldstick) { currentlystickingview = viewthatshouldstick; if (getstringtagforview(currentlystickingview).contains(flag_hastransparancy)) { hideview(currentlystickingview); } if (((string) currentlystickingview.gettag()).contains(flag_nonconstant)) { post(invalidaterunnable); } } private void stopstickingcurrentlystickingview() { if (getstringtagforview(currentlystickingview).contains(flag_hastransparancy)) { showview(currentlystickingview); } currentlystickingview = null; removecallbacks(invalidaterunnable); } /** * notify that the sticky attribute has been added or removed from one or * more views in the view hierarchy */ public void notifystickyattributechanged() { notifyhierarchychanged(); } private void notifyhierarchychanged() { if (currentlystickingview != null) { stopstickingcurrentlystickingview(); } stickyviews.clear(); findstickyviews(getchildat(0)); dothestickything(); invalidate(); } private void findstickyviews(view v) { if (v instanceof viewgroup) { viewgroup vg = (viewgroup) v; for (int i = 0; i < vg.getchildcount(); i++) { string tag = getstringtagforview(vg.getchildat(i)); if (tag != null && tag.contains(sticky_tag)) { stickyviews.add(vg.getchildat(i)); } else if (vg.getchildat(i) instanceof viewgroup) { findstickyviews(vg.getchildat(i)); } } } else { string tag = (string) v.gettag(); if (tag != null && tag.contains(sticky_tag)) { stickyviews.add(v); } } } private string getstringtagforview(view v) { object tagobject = v.gettag(); return string.valueof(tagobject); } private void hideview(view v) { if (build.version.sdk_int >= 11) { v.setalpha(0); } else { alphaanimation anim = new alphaanimation(1, 0); anim.setduration(0); anim.setfillafter(true); v.startanimation(anim); } } private void showview(view v) { if (build.version.sdk_int >= 11) { v.setalpha(1); } else { alphaanimation anim = new alphaanimation(0, 1); anim.setduration(0); anim.setfillafter(true); v.startanimation(anim); } } /** * 设置悬浮高度 * @param height */ public void setsticktop(int height) { min_stick_top = height; } /** * 解决vviewpager在scrollview滑动冲突的问题 */ // 滑动距离及坐标 private float xdistance, ydistance, xlast, ylast; @override public boolean onintercepttouchevent(motionevent ev) { switch (ev.getaction()) { case motionevent.action_down: xdistance = ydistance = 0f; xlast = ev.getx(); ylast = ev.gety(); break; case motionevent.action_move: final float curx = ev.getx(); final float cury = ev.gety(); xdistance += math.abs(curx - xlast); ydistance += math.abs(cury - ylast); // com.ihaveu.utils.log.i("test", "curx:"+curx+",cury:"+cury+",xlast:"+xlast+",ylast:"+ylast); // xlast = curx; // ylast = cury; if (xdistance > ydistance) { return false; } } return super.onintercepttouchevent(ev); } }
接下来是调用自定义控件了,用到两个关键的方法。statusbarutil.settranslucentforimageview(mainactivity.this, 0, title)和lltitle.setbackgroundcolor(color.argb((int) alpha, 227, 29, 26))分别设置状态栏和标题栏的颜色。
package com.xiaoyuan; import android.graphics.color; import android.os.bundle; import android.support.v7.app.appcompatactivity; import android.view.view; import android.view.viewtreeobserver; import android.widget.framelayout; import android.widget.linearlayout; import android.widget.relativelayout; import android.widget.textview; import com.jaeger.library.statusbarutil; public class mainactivity extends appcompatactivity implements view.onclicklistener, stickyscrollview.onscrollchangedlistener { textview onetextview, twotextview; private stickyscrollview stickyscrollview; private int height; private linearlayout llcontent; private relativelayout lltitle; private framelayout framelayout; private textview title; @override protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.activity_main); initview(); initlisteners(); } /** * 初始化view */ private void initview() { stickyscrollview = (stickyscrollview) findviewbyid(r.id.scrollview); framelayout = (framelayout) findviewbyid(r.id.tabmaincontainer); title = (textview) findviewbyid(r.id.title); onetextview = (textview) findviewbyid(r.id.infotext); llcontent = (linearlayout) findviewbyid(r.id.ll_content); lltitle = (relativelayout) findviewbyid(r.id.ll_good_detail); onetextview.setonclicklistener(this); twotextview = (textview) findviewbyid(r.id.secondtext); twotextview.setonclicklistener(this); stickyscrollview.setonscrolllistener(this); statusbarutil.settranslucentforimageview(mainactivity.this, 0, title); framelayout.layoutparams params = (framelayout.layoutparams) lltitle.getlayoutparams(); params.setmargins(0, getstatusheight(), 0, 0); lltitle.setlayoutparams(params); //默认设置一个frg getsupportfragmentmanager().begintransaction().replace(r.id.tabmaincontainer, fragment.newinstance()).commit(); } /** * 获取状态栏高度 * * @return */ private int getstatusheight() { int resourceid = mainactivity.this.getresources().getidentifier("status_bar_height", "dimen", "android"); return getresources().getdimensionpixelsize(resourceid); } @override public void onclick(view v) { if (v.getid() == r.id.infotext) { getsupportfragmentmanager().begintransaction().replace(r.id.tabmaincontainer, fragment.newinstance()).commit(); } else if (v.getid() == r.id.secondtext) { getsupportfragmentmanager().begintransaction().replace(r.id.tabmaincontainer, fragment1.newinstance()).commit(); } } private void initlisteners() { //获取内容总高度 final viewtreeobserver vto = llcontent.getviewtreeobserver(); vto.addongloballayoutlistener(new viewtreeobserver.ongloballayoutlistener() { @override public void ongloballayout() { height = llcontent.getheight(); //注意要移除 llcontent.getviewtreeobserver() .removeglobalonlayoutlistener(this); } }); //获取fragment高度 viewtreeobserver viewtreeobserver = framelayout.getviewtreeobserver(); viewtreeobserver.addongloballayoutlistener(new viewtreeobserver.ongloballayoutlistener() { @override public void ongloballayout() { height = height - framelayout.getheight(); //注意要移除 framelayout.getviewtreeobserver() .removeglobalonlayoutlistener(this); } }); //获取title高度 viewtreeobserver viewtreeobserver1 = lltitle.getviewtreeobserver(); viewtreeobserver1.addongloballayoutlistener(new viewtreeobserver.ongloballayoutlistener() { @override public void ongloballayout() { height = height - lltitle.getheight() - getstatusheight();//计算滑动的总距离 stickyscrollview.setsticktop(lltitle.getheight() + getstatusheight());//设置距离多少悬浮 //注意要移除 lltitle.getviewtreeobserver() .removeglobalonlayoutlistener(this); } }); } @override public void onscrollchanged(int l, int t, int oldl, int oldt) { if (t <= 0) { lltitle.setbackgroundcolor(color.argb((int) 0, 255, 255, 255)); } else if (t > 0 && t <= height) { float scale = (float) t / height; int alpha = (int) (255 * scale); lltitle.setbackgroundcolor(color.argb((int) alpha, 227, 29, 26));//设置标题栏的透明度及颜色 statusbarutil.settranslucentforimageview(mainactivity.this, alpha, title);//设置状态栏的透明度 } else { statusbarutil.settranslucentforimageview(mainactivity.this, 0, title); lltitle.setbackgroundcolor(color.argb((int) 255, 227, 29, 26)); statusbarutil.settranslucentforimageview(mainactivity.this, 255, title); } } }
最后demo下载:demo
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。