引导指示界面是个什么鬼东西?一张图即明了:android
其实就是给刚安装你的软件的用户指示如何使用的一个蒙层,具备如下特色:ide
这一个小小的界面实现起来有一些小的诀窍,使用了ViewStub和SharePrefrence,下面一步步展现如何实现。布局
写布局ui
第一步就是写出这个展现出来效果的布局文件,这里例子很简单,就是一个全屏的.9半透明黑色图加上一个白色文字图片,图片居中。这一步直接给出代码。spa
根据你的状况本身实现本身所须要的布局。code
layout\guide_root_slide_left_right.xmlxml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" android:focusable="true" android:clickable="true" android:id="@+id/guide_root" android:background="@drawable/bg_dark" > <ImageView android:layout_width="wrap_content" android:layout_height="wrap_content" android:src="@drawable/img_slide" android:layout_centerInParent="true" /> </RelativeLayout>
使用ViewStubblog
为何使用ViewStub?首先看下咱们的需求,第一是这个页面是动态根据条件呈现的,第二是它并不重要出现过一次后就再也不需了,由于但愿它不要占多少内存。以此来看,ViewStub就是实现这个引导指示层的最佳控件。生命周期
对于在运行时决定可见性的界面咱们一般的作法是:事件
这样子没什么不可,可是带来的问题是之后每次进这个界面,系统都会为这个view分配内存而且实例化,从而拖慢了速度,耗费资源(事实上咱们只想让它显示仅仅一次就不要了)。而ViewStub呢?它是一个轻量级的View,相似于一个占位符。给他指定一个布局,它默认并不会inflate出来,直到你想让它显示出来的时候才会inflate你所指定的布局从而延迟分配了内存(相似于延迟加载)。
因为咱们的半透明指示层是要蒙住全屏的,并且才原来的布局界面之上(布局树里面的控件是写在上面位置的先展现,写在下面位置的后展现),因此咱们的原来的根布局须要为RelativeLayout,同时在根布局的最下面写上ViewStub:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/root" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> <!-- 原来的Activity内容--> ... <ViewStub android:id="@+id/guide_root_slide" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_centerInParent="true" android:layout="@layout/guide_root_slide_left_right"/> </RelativeLayout>
这里ViewStub能够看成是一个普通的View来加入到布局文件里面,同时给他的layout参数执行咱们实际想要inflate出来的布局。等于给占位符设置一个“目标”。
增长逻辑代码
在你的activity代码中,得到这个ViewStub的引用:
ViewStub stubGuideSlide; // onCreate stubGuideSlide = (ViewStub) findViewById(R.id.guide_root_slide);
而后写一个方法,在你的运行判断逻辑(好比某个按钮的点击回调)里面执行这个方法,这里写上伪代码:
// some on Click listener ... showGuideSlide(); ... private void showGuideSlide(){ if(若是第一次到这里) 展现GuideSlide引导指示层 else 不展现 }
如何判断是否第一次走到这里呢?咱们能够用SharePreference,咱们能够随便定义属于这张引导指示层的key,而后判断他是否存在。若是不存在表示第一次进入,进入后咱们把这个key对应的SharePeference随便设一个值,下回就不会走到这里了:(showGuideSlide的完整代码以下)
private void showGuideSlide() { if (SPUtils.contains(mContext, Constant.GuideVisibilityKey.ROOT_FRAGMENT_SLIDE)) { return; } try { final View guideSlideView = stubGuideSlide.inflate(); RelativeLayout rl = (RelativeLayout) guideSlideView.findViewById(R.id.guide_root); if (rl != null) { rl.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { guideSlideView.setVisibility(View.GONE); } }); } } catch (Exception e) { e.printStackTrace(); } SPUtils.put(mContext, Constant.GuideVisibilityKey.ROOT_FRAGMENT_SLIDE, true); }
上述代码须要解释几个地方: