Android-動態佈局載入
阿新 • • 發佈:2018-12-18
動態佈局核心.
編譯性佈局.佈局要求是已經編譯好的,也就是下圖所示.如何編譯.先打包成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) {