各种长见识涨姿势Android知识Android开发

Android 动态解析布局,实现制作多套主题

2016-11-22  本文已影响692人  Venus_明

问题背景

之前做过一个项目(随心壁纸),主要展示过去每期的壁纸主题以及相应的壁纸,而且策划要求,最好可以动态变换主题呈现方式,这样用户体验会比较好。嗯,好吧,策划的话,咱们也没法反驳,毕竟这样搞,确实很不错。于是开始去研究这方面的东西。

解决思路

首先,我想到的是照片墙效果,改变图片就能有不同的呈现方式。可是这样的话,文字以及更深层的自定义效果,就无法实现了。然后,思考了下,决定仿照android原生布局文件解析方式,自己去动态解析布局。

具体实现

先来看下android 原生布局文件解析流程:

第一步

调用LayoutInflater的inflate函数解析xml文件得到一个view,然后来看看inflate函数:


//使用常见的API方法去解析xml布局文件 
LayoutInflater layoutInflater = (LayoutInflater)getSystemService(); 
View root = layoutInflater.inflate(R.layout.main, null,false);

第二步:

在inflate函数中,获取一个XmlResourceParser来解析xml布局文件,再往下跟inflate(parser, root, attachToRoot):

public View inflate(int resource, ViewGroup root, boolean attachToRoot) { 
        if (DEBUG) 
              System.out.println("INFLATING from resource: " + resource); 
        XmlResourceParser parser = getContext().getResources().getLayout(resource); 
        try { 
            return inflate(parser, root, attachToRoot); 
        } finally { 
            parser.close(); 
        } 
}

第三步:

inflate函数中会根据布局的节点名创建根视图,接着根据方法中传进来的root参数,判断是否为空,如果不为null,则为该根视图赋予外面父视图的布局参数。接着调用rInflate函数来为根视图添加所有字节点。


public View inflate(XmlPullParser parser, ViewGroup root, boolean attachToRoot) {
    synchronized(mConstructorArgs) {
        final AttributeSet attrs = Xml.asAttributeSet(parser);
        Context lastContext = (Context) mConstructorArgs[0];
        mConstructorArgs[0] = mContext; //该mConstructorArgs属性最后会作为参数传递给View的构造函数
        View result = root;

        try {
            // Look for the root node.
            int type;
            while ((type = parser.next()) != XmlPullParser.START_TAG && type != XmlPullParser.END_DOCUMENT) {
                // Empty
            }

            if (type != XmlPullParser.START_TAG) {
                throw new InflateException(parser.getPositionDescription() + ": No start tag found!");
            }

            final String name = parser.getName(); //节点名,即API中的控件或者自定义View完整限定名
            if (TAG_MERGE.equals(name)) {
                if (root == null || !attachToRoot) {
                    throw new InflateException("<merge /> can be used only with a valid " + "ViewGroup root and attachToRoot=true");
                }

                rInflate(parser, root, attrs, false);
            } else {
                // Temp is the root view that was found in the xml
                View temp;
                if (TAG_1995.equals(name)) {
                    temp = new BlinkLayout(mContext, attrs);
                } else {
                    temp = createViewFromTag(root, name, attrs);
                }

                ViewGroup.LayoutParams params = null;

                if (root != null) {
                    // Create layout params that match root, if supplied
                    params = root.generateLayoutParams(attrs);
                    if (!attachToRoot) {
                        // Set the layout params for temp if we are not
                        // attaching. (If we are, we use addView, below)
                        temp.setLayoutParams(params);
                    }
                }

                // Inflate all children under temp
                rInflate(parser, temp, attrs, true);

                // We are supposed to attach all the views we found (int temp)
                // to root. Do that now.
                if (root != null && attachToRoot) {
                    root.addView(temp, params);
                }

                // Decide whether to return the root that was passed in or the
                // top view found in xml.
                if (root == null || !attachToRoot) {
                    result = temp;
                }
            }

        } catch(XmlPullParserException e) {
            //...
        } finally {
            // Don't retain static reference on context.
            mConstructorArgs[0] = lastContext;
            mConstructorArgs[1] = null;
        }

        return result;
    }
}

第四步:

rInflate方法中主要是去递归调用布局文件根视图的子节点。将解析得到的view添加到parentView。

/**
     * Recursive method used to descend down the xml hierarchy and instantiate
     * views, instantiate their children, and then call onFinishInflate().
     */
void rInflate(XmlPullParser parser, View parent, final AttributeSet attrs, boolean finishInflate) throws XmlPullParserException,
IOException {

    final int depth = parser.getDepth();
    int type;

    while (((type = parser.next()) != XmlPullParser.END_TAG || parser.getDepth() > depth) && type != XmlPullParser.END_DOCUMENT) {

        if (type != XmlPullParser.START_TAG) {
            continue;
        }

        final String name = parser.getName();

        if (TAG_REQUEST_FOCUS.equals(name)) { //处理<requestFocus />标签
            parseRequestFocus(parser, parent);
        } else if (TAG_INCLUDE.equals(name)) { //处理<include />标签 
            if (parser.getDepth() == 0) {
                throw new InflateException("<include /> cannot be the root element");
            }
            parseInclude(parser, parent, attrs); //解析<include />节点
        } else if (TAG_MERGE.equals(name)) { //处理<merge />标签  
            throw new InflateException("<merge /> must be the root element");
        } else if (TAG_1995.equals(name)) { //处理<blink />标签
            final View view = new BlinkLayout(mContext, attrs);
            final ViewGroup viewGroup = (ViewGroup) parent;
            final ViewGroup.LayoutParams params = viewGroup.generateLayoutParams(attrs);
            rInflate(parser, view, attrs, true);
            viewGroup.addView(view, params);
        } else {
            //根据节点名构建一个View实例对象
            final View view = createViewFromTag(parent, name, attrs);
            final ViewGroup viewGroup = (ViewGroup) parent;
            //调用generateLayoutParams()方法返回一个LayoutParams实例对象,
            final ViewGroup.LayoutParams params = viewGroup.generateLayoutParams(attrs);
            rInflate(parser, view, attrs, true); //继续递归调用 
            viewGroup.addView(view, params); //OK,将该View以特定LayoutParams值添加至父View
        }
    }

    if (finishInflate) parent.onFinishInflate(); //完成解析过程,通知..
}

在rInflate方法的37行代码中,final View view = createViewFromTag(parent, name, attrs),由节点名等参数构建的一个view实例对象,由于下面的代码会越来越大,就直接贴出主要实现函数,具体可参见Android源码。

/**
     * default visibility so the BridgeInflater can override it.
     */
View createViewFromTag(View parent, String name, AttributeSet attrs) {

    //...
    try {
        //...
        if (view == null) {
            if ( - 1 == name.indexOf('.')) {
                view = onCreateView(parent, name, attrs);
            } else {
                view = createView(name, null, attrs);
            }
        }

        return view;

    } catch(InflateException e) {
        //...
    }
}

然后再往onCreateView()中跟下去,会发现,它其实主要还是实现了createView();所以我们直接CreateView实现。

protected View onCreateView(String name, AttributeSet attrs) throws ClassNotFoundException {
    return createView(name, "android.view.", attrs);
}

在createView(name, “android.view.”, attrs)中,会用反射机制创建android.view.XXX(比如TextView)的实例对象,并返回。
这也就是LayoutInflater.inflate的布局解析流程了
当你熟悉了流程,接下来为你讲解的,随心壁纸的动态解析布局思路,你就基本懂的大半了
由于最初的layoutInflater.inflate(R.layout.main, null,false)函数,传入的是R.layout.main资源id,而对于我们的项目,布局文件是在线更新的,是间接存储在sd卡中,所以这种解析方式就不行了,所幸LayoutInflater的api方法还提供了inflate(XmlPullParser parser, ViewGroup root,boolean attachToRoot)解析,根据文件保存路径生成需要的xmlPullParser:

public XmlPullParser getXmlPullParser(String resource) {
    XmlPullParser parser = Xml.newPullParser();
    try {
        // InputStream is=mContext.getAssets().open("transfer_main.xml");
        FileInputStream is = new FileInputStream(resource);

        parser.setInput(is, "utf-8");
    } catch(Exception e) {
        e.printStackTrace();
    }
    return parser;
}

后面的第二步等其实都是一样的流程(我会在后面贴出实现demo)。但是有一点需要特别注意,也是必须实现的一点:
因为所下载的布局文件得到的解析流,跟程序里res/layout/xxx.xml有一个非常大的不同,资源id!!程序中的布局文件,里面所注册的id以及text,或者drawble都是可以真实在R目录下找到的,而下载的布局文件是没有这个福利的,它是我们外面生成的,并没有经过apk编译过程。所以为了能得到下载文件里的布局各个id,我们需要自己实现对View的属性解析。

protected View onCreateView(String name, AttributeSet attrs) throws ClassNotFoundException {
    // return createView(name, "android.view.", attrs);
    return createView(name, "com.xxx.xxxx.viewanalysis.view.VA", attrs); 
    //比如com.xx.view.VATextView 项目中自定义view 继承自TextView
}

布局中的控件代码编写,可以是TextView等原生的,也可以是自定义过的,因为TextView经过加前缀,再通过后面的反射方法,也会跑到相应的自定义方法,返回一个自定义View对象。不过因为最终都是要跑自定义view,所以要求我们需要事先定义好会用到的,目前我定义好了9种,比如Button,GridView,RelativeLayout等。如果没有定义的view直接用在文件中,会导致编译出错(ClassNotFoundException)。
VAButton类实现

public class VAButton extends android.widget.Button {

    public VAButton(Context context, AttributeSet attrs) {
        super(context);
        setAttributeSet(attrs);
    }

    @SuppressWarnings("deprecation") public void setAttributeSet(AttributeSet attrs) {

        HashMap < String,
        ParamValue > map = YDResource.getInstance().getViewMap();

        int count = attrs.getAttributeCount();
        for (int i = 0; i < count; i++) {
            ParamValue key = map.get(attrs.getAttributeName(i));
            if (key == null) {
                continue;
            }
            switch (key) {
            case id:
                this.setTag(attrs.getAttributeValue(i));
                break;
            case text:
                String value = YDResource.getInstance().getString(attrs.getAttributeValue(i));
                this.setText(value);
                break;
                //case...  
            default:
                break;
            }
        }
    }

Ps: view id通过设置标志在外面可以获取到(具体可以看demo) 属性方面的解析,我就不多说了,网上的资料很多,有兴趣的可以去了解下。

demo效果图:
项目中的效果图: 主题1 主题2
接下来看看demo中的代码结构: 此为截图,因为老项目了,大家伙见谅

这里的代码主体在于YDLayoutInflater与ParamValue的实现,以及9种自定义view。 YDLayoutInflater主要是仿照LayoutInflater实现的,做了一些适应布局文件的修改处理,上面已经说过了。
具体的代码下载地址
动态解析布局的思路讲完了,应用到项目中,效果也不错,虽然有一些限制规范,但是对于总体的功能设计是无关大雅的。关于主题呈现动态更新,如果有大神有更好的方式,可以给我留言!

如果觉得此文不错,麻烦帮我点下“喜欢”。么么哒!

上一篇下一篇

猜你喜欢

热点阅读