源码分析

 @RemoteView
public final class ViewStub extends View {
private int mInflatedId;
private int mLayoutResource; private WeakReference<View> mInflatedViewRef; private LayoutInflater mInflater;
private OnInflateListener mInflateListener; public ViewStub(Context context) {
this(context, );
} /**
* Creates a new ViewStub with the specified layout resource.
*
* @param context The application's environment.
* @param layoutResource The reference to a layout resource that will be inflated.
*/
public ViewStub(Context context, @LayoutRes int layoutResource) {
this(context, null); mLayoutResource = layoutResource;
} public ViewStub(Context context, AttributeSet attrs) {
this(context, attrs, );
} public ViewStub(Context context, AttributeSet attrs, int defStyleAttr) {
this(context, attrs, defStyleAttr, );
} public ViewStub(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context); final TypedArray a = context.obtainStyledAttributes(attrs,
R.styleable.ViewStub, defStyleAttr, defStyleRes);
mInflatedId = a.getResourceId(R.styleable.ViewStub_inflatedId, NO_ID);
mLayoutResource = a.getResourceId(R.styleable.ViewStub_layout, );
mID = a.getResourceId(R.styleable.ViewStub_id, NO_ID);
a.recycle(); setVisibility(GONE); // 默认不可见
setWillNotDraw(true); // 如果View不绘制任何内容,设置这个标记可以优化性能,默认View没有设置这个标记,如果重写onDraw,就不要设置这个标记
} @Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
setMeasuredDimension(, ); // 测量时尺寸为0
} @Override
public void draw(Canvas canvas) { // 不绘制内容
} @Override
protected void dispatchDraw(Canvas canvas) {
}
..... 省去部分代码 private View inflateViewNoAdd(ViewGroup parent) {
final LayoutInflater factory;
if (mInflater != null) {
factory = mInflater;
} else {
factory = LayoutInflater.from(mContext);
} // 通过inflate填充布局
final View view = factory.inflate(mLayoutResource, parent, false); if (mInflatedId != NO_ID) {
view.setId(mInflatedId);
}
return view;
} private void replaceSelfWithView(View view, ViewGroup parent) {
final int index = parent.indexOfChild(this);
parent.removeViewInLayout(this); // 移除ViewStub,后面不能在inflate final ViewGroup.LayoutParams layoutParams = getLayoutParams(); // 获得ViewStub的布局参数
if (layoutParams != null) {
parent.addView(view, index, layoutParams); // 把ViewStub指定的布局添加到parent中
} else {
parent.addView(view, index);
}
} /**
* Inflates the layout resource identified by {@link #getLayoutResource()}
* and replaces this StubbedView in its parent by the inflated layout resource.
*
* @return The inflated layout resource.
*
*/
public View inflate() {
final ViewParent viewParent = getParent(); // 获取ViewStub的parent if (viewParent != null && viewParent instanceof ViewGroup) {
if (mLayoutResource != ) {
final ViewGroup parent = (ViewGroup) viewParent;
final View view = inflateViewNoAdd(parent);
replaceSelfWithView(view, parent); mInflatedViewRef = new WeakReference<>(view);
if (mInflateListener != null) {
mInflateListener.onInflate(this, view);
} return view;
} else {
throw new IllegalArgumentException("ViewStub must have a valid layoutResource");
}
} else {
throw new IllegalStateException("ViewStub must have a non-null ViewGroup viewParent");
}
} /**
* Specifies the inflate listener to be notified after this ViewStub successfully
* inflated its layout resource.
*
* @param inflateListener The OnInflateListener to notify of successful inflation.
*
* @see android.view.ViewStub.OnInflateListener
*/
public void setOnInflateListener(OnInflateListener inflateListener) {
mInflateListener = inflateListener;
} /**
* Listener used to receive a notification after a ViewStub has successfully
* inflated its layout resource.
*
* @see android.view.ViewStub#setOnInflateListener(android.view.ViewStub.OnInflateListener)
*/
public static interface OnInflateListener {
/**
* Invoked after a ViewStub successfully inflated its layout resource.
* This method is invoked after the inflated view was added to the
* hierarchy but before the layout pass.
*
* @param stub The ViewStub that initiated the inflation.
* @param inflated The inflated View.
*/
void onInflate(ViewStub stub, View inflated);
} /** @hide **/
public class ViewReplaceRunnable implements Runnable {
public final View view; ViewReplaceRunnable(View view) {
this.view = view;
} @Override
public void run() {
replaceSelfWithView(view, (ViewGroup) getParent());
}
}
}

这是什么玩应儿呢?其实就是一个轻量级的页面,我们通常使用它来做预加载处理,来改善页面加载速度和提高流畅性,ViewStub本身不会占用层级,它最终会被它指定的层级取代。 
在一些场合取代android:visibility=”gone”的用法,因为被gone掉的布局不断是会同时创建对象的。那为什么使用ViewStub就高效呢, 
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { 
setMeasuredDimension(0, 0); 
}

@Override 
public void draw(Canvas canvas) { 

由onMeasure()方法和draw()方法可以看出, ViewStub的初始宽高都是零,所以他开始不会占用空间,其次draw()方法也没有执行任何的绘制,由这两个方法就可以看出,ViewStub的确很高效。 
在代码中要操纵ViewStub的时候,要首先使用viewstub.inflate()方法,将其所拥有的View初始化进去。否则会报空指针错误。 
但ViewStub也不是万能的,下面总结下ViewStub能做的事儿和什么时候该用ViewStub,什么时候该用可见性的控制。

首先来说说ViewStub的一些特点:

. ViewStub只能Inflate一次,之后ViewStub对象会被置为空。按句话说,某个被ViewStub指定的布局被Inflate后,就不会够再通过ViewStub来控制它了。
. ViewStub只能用来Inflate一个布局文件,而不是某个具体的View,当然也可以把View写在某个布局文件中。 基于以上的特点,那么可以考虑使用ViewStub的情况有:
. 在程序的运行期间,某个布局在Inflate后,就不会有变化,除非重新启动。
因为ViewStub只能Inflate一次,之后会被置空,所以无法指望后面接着使用ViewStub来控制布局。所以当需要在运行时不止一次的显示和隐藏某个布局,那么ViewStub是做不到的。这时就只能使用View的可见性来控制了。
. 想要控制显示与隐藏的是一个布局文件,而非某个View。
因为设置给ViewStub的只能是某个布局文件的Id,所以无法让它来控制某个View。
所以,如果想要控制某个View(如Button或TextView)的显示与隐藏,或者想要在运行时不断的显示与隐藏某个布局或View,只能使用View的可见性来控制。

布局优化之ViewStub源码分析的更多相关文章

  1. ViewStub源码分析

    ViewStub是一种特殊的View,Android官方给出的解释是:一种不可见的(GONE).size是0的占位view,多用于运行时 延迟加载的,也就是说真正需要某个view的时候.在实际项目中, ...

  2. invalidate和requestLayout方法源码分析

    invalidate方法源码分析 在之前分析View的绘制流程中,最后都有调用一个叫invalidate的方法,这个方法是啥玩意?我们来看一下View类中invalidate系列方法的源码(ViewG ...

  3. 消息队列的一些场景及源码分析,RocketMQ使用相关问题及性能优化

    前文目录链接参考: 消息队列的一些场景及源码分析,RocketMQ使用相关问题及性能优化 https://www.cnblogs.com/yizhiamumu/p/16694126.html 消息队列 ...

  4. Netty源码分析第2章(NioEventLoop)---->第5节: 优化selector

    Netty源码分析第二章: NioEventLoop   第五节: 优化selector 在剖析selector轮询之前, 我们先讲解一下selector的创建过程 回顾之前的小节, 在创建NioEv ...

  5. spark源码分析以及优化

    第一章.spark源码分析之RDD四种依赖关系 一.RDD四种依赖关系 RDD四种依赖关系,分别是 ShuffleDependency.PrunDependency.RangeDependency和O ...

  6. HotSpot源码分析之C++对象的内存布局

    HotSpot采用了OOP-Klass模型来描述Java类和对象.OOP(Ordinary Object Pointer)指的是普通对象指针,而Klass用来描述对象的具体类型.为了更好理解这个模型, ...

  7. 【集合框架】JDK1.8源码分析之HashMap(一)

    一.前言 在分析jdk1.8后的HashMap源码时,发现网上好多分析都是基于之前的jdk,而Java8的HashMap对之前做了较大的优化,其中最重要的一个优化就是桶中的元素不再唯一按照链表组合,也 ...

  8. [Android实例] Scroll原理-附ScrollView源码分析

    想象一下你拿着放大镜贴很近的看一副巨大的清明上河图, 那放大镜里可以看到的内容是很有限的, 而随着放大镜的上下左右移动,就可以看到不同的内容了 android中手机屏幕就相当于这个放大镜, 而看到的内 ...

  9. YII框架源码分析(百度PHP大牛创作-原版-无广告无水印)

           YII 框架源码分析    百度联盟事业部——黄银锋 目 录 1. 引言 3 1.1.Yii 简介 3 1.2.本文内容与结构 3 2.组件化与模块化 4 2.1.框架加载和运行流程 4 ...

随机推荐

  1. 毕业不到一年,绩效打了个D!

    周末了,和大家来聊聊程序员工作态度的问题. 说说栈长的事迹吧,这是好多年前的事了,那时候,栈长才毕业不到一年,那次绩效打了个D!事后,我很气愤啊,我那时还在博客上写文章怒骂了部门经理,现在想起来,真是 ...

  2. LeetCode20:validParentheses

    validParentheses 题目描述 Given a string containing just the characters '(', ')', '{', '}', '[' and ']', ...

  3. JS中部分不常用小功能记录

    1.serializeArray()在表单中使用,必须在form标签中,需要手机的元素要有name属性.源生JS将对象转成json   resulrMK = JSON.stringify(resulr ...

  4. Docker学习之1—基础及安装

    Docker介绍: Docker 是一个开源的应用容器引擎,让开发者可以打包他们的应用以及依赖包到一个可移植的容器中,然后发布到任何流行的 Linux 机器上,也可以实现虚拟化.容器是完全使用沙箱机制 ...

  5. spark最新源码下载并导入到开发环境下助推高质量代码(Scala IDEA for Eclipse和IntelliJ IDEA皆适用)(以spark2.2.0源码包为例)(图文详解)

    不多说,直接上干货! 前言   其实啊,无论你是初学者还是具备了有一定spark编程经验,都需要对spark源码足够重视起来. 本人,肺腑之己见,想要成为大数据的大牛和顶尖专家,多结合源码和操练编程. ...

  6. Java工程师修炼之路(从小白到BAT的两年学习历程)

    ​ 作者:陆小凤 文章首发于:微信公众号[程序员江湖] 前言 在下本是跨专业渣考研的985渣硕一枚,经历研究生两年的学习积累,有幸于2019秋季招聘中拿到几个公司的研发岗offer,包括百度,阿里,腾 ...

  7. vue-07-自定义指令

    1, 全局指令 在main.js中引入 // 注册一个全局自定义指令 `v-focus` Vue.directive('focus', { // 当被绑定的元素插入到 DOM 中时…… inserte ...

  8. Cookie提要

    Cookie的基本概念和设置  Cookie在远程浏览器端存储数据并以此跟踪和识别用户的机制.从实现上说,Cookie是存储在客户端上的小段数据,浏览器(即客户端)通过HTTP协议和服务器端进行Coo ...

  9. SpringBoot(5) SpringBoot个性化启动

    1.在类路径下增加一个banner.txt,里面是启动要输出的信息 自定义banner在线生成工具: http://www.bootschool.net/ascii _ _ _ _ __ | | __ ...

  10. MySQL的使用及优化

    前言 最近听了公司里的同事做的技术分享,然后觉得对自己还是挺有帮助的.都是一些日常需要注意的地方,我们目前在开发过程中,其实用不到MySQL太深的内容的.只是能适用我们日常开发的知识就可以了.所以我将 ...