Android-动态布局加载

动态布局核心.

编译性布局.布局要求是已经编译好的,也就是下图所示.如何编译.先打包成apk.然后进行解压,就能获得编译后的资源文件.

 通过xmlPullParser进行解析,主要是LayoutInflater中的第二个方法以及第四个方法.通过xmlPullParser解析进行.

解析方法:

注:其中解析的文件需要.xml.并且是编译完成的.我这边用了判断.如果没有.xml.则会自动加上.此方法是解析Assets中布局文件.

public XmlPullParser getLayoutXmlPullParser(String path) {
        XmlPullParser xmlPullParser = null;
        AssetManager  assetManager  = mContext.getAssets();
        try {
            if (!path.endsWith(".xml")) {
                path = path + ".xml";
            }
            xmlPullParser = assetManager.openXmlResourceParser("assets/" + path);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return xmlPullParser;
    }

解析Assets中的xml资源文件:

注:此方法主要是针对shape,vectoer之类的资源.可以解析成Drawable对象进行返回.这边也是编译后的布局.

 public Drawable getDrawableXmlPullParserAfter(String name) {
        Drawable     drawable     = null;
        AssetManager assetManager = mContext.getAssets();
        try {
            if (!name.endsWith(".xml")) {
                name = name + ".xml";
            }
            XmlPullParser xmlPullParser = assetManager.openXmlResourceParser("assets/" + name);
            drawable = Drawable.createFromXml(mContext.getResources(), xmlPullParser);

        } catch (Exception e) {
            e.printStackTrace();
        }
        return drawable;

    }

注: 此处通过openXmlResourceParser解析的,不能省略assets/,否则会找不到此资源文件

解析图片: 

注: 这个方法就可以不加assets/,因为是通过open打开的,

public static Bitmap getBitmapForName(String filename) {
        Bitmap bitmap = null;
        try {
            InputStream is = mContext.getAssets().open(filename);
            bitmap = BitmapFactory.decodeStream(is);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            return bitmap;
        }
    }

寻找资源方法,

view中有一个view.findViewWithTag方法.通过tag方法来获取

 public final <T extends View> T findViewWithTag(Object tag) {

猜你喜欢

转载自blog.csdn.net/ci250454344/article/details/84063142