最近由于項目開發使用到了動態布局,因為打包sdk ,sdk 這塊activity 需要一些layout 文件 。而做過sdk 開發的小伙伴應該知道,layout 文件是不能打包到jar 中的。當然了aar 除外。由于項目使用的還是jar包,所以怎么解決layout文件是個問題,一開始想到的辦法就是把layout 文件發給客戶。但是這種方法顯然不太合適后來就發現了Android 其實提供了一個方法可以加載xml布局文件,就是使用inflate(XmlPullParser parser, ViewGroup root)這個方法,網上找了大批的文章,其中還是找到了兩篇簡單描寫了下這個解析的過程但是在使用過程中還是出現了幾個問題 :
1 如何拿到XmlPullParser 對象
拿到這個對象倒是不難我們通過 AssetsManger 就可以輕易獲取XmlResourceParser openXmlResourceParser(String fileName)
但是注意這里有個問題就是filename 要加上”assets\”前綴不然會報 FileNotFound異常
2 發現解析不了xml 布局文件
openxmlresourceparser 方法報錯,為什么呢。查到資料是因為這個方法只能解析編譯后的xml文件,那么什么事編譯后的xml文件,就是生成的apk 解壓后 拿到的xml就是編譯后的。所以我們放在assets 中的xml 都要是編譯后的文件。目前還沒有找到Android有別的工具可以專門編譯xml 文件
3 解析到了view 如何拿到里面的子view 通過id 不行啊
這是肯定的不是在layout文件夾下的不會有id 索引所以你不能通過id 來find 。那么如何拿到子view ,后來發現了有人解決這個問題就是通過findViewWithTag 這個方法可以通過xml view 下配置的tag 來獲取
以上問題解決后就完美拿到了xml 的布局view 文件 可以動態設置給activity了。下面我把源碼貼上來需要的朋友可以參考下。
import android.content.Context;
import android.content.res.AssetManager;
import android.content.res.XmlResourceParser;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.view.LayoutInflater;
import android.view.View;
import java.io.IOException;
import java.io.InputStream;
/**
* Created by yuge on 2017/11/8.
*/
public class AssetsViewHelper {
private static Context mcontext;
private static AssetsViewHelper assetsViewHelper;
/**
* assets 目錄前綴
*/
private static String assetsFile="assets/";
private AssetsViewHelper(){
}
public static AssetsViewHelper width(Context context){
mcontext=context.getApplicationContext();
if(assetsViewHelper==null){
synchronized (AssetsViewHelper.class){
if(assetsViewHelper==null){
assetsViewHelper=new AssetsViewHelper();
}
}
}
return assetsViewHelper;
}
/**
* 獲取layout方法
* @param filename
* @return
*/
public View getAssetsLayout(String filename) {
AssetManager am = mcontext.getResources().getAssets();
try {
XmlResourceParser parser = am.openXmlResourceParser(assetsFile + "activity_main.xml");
LayoutInflater inflater = (LayoutInflater) mcontext.getSystemService(mcontext.LAYOUT_INFLATER_SERVICE);
View inflate = inflater.inflate(parser, null);
return inflate;
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
/**
* 根據 tag 獲取 view 對象
* @param viewGroup 父容器也就是activity的根布局
* @param tag
* @return
*/
public View getViewByTag(View viewGroup,Object tag){
return viewGroup.findViewWithTag(object);
}
/**
* 獲取assets 中圖片的方法
* @param fileName
* @return
*/
Bitmap getImageFromAssetsFile(String fileName)
{
Bitmap image = null;
AssetManager am = mcontext.getResources().getAssets();
try
{
InputStream is = am.open(assetsFile+fileName);
image = BitmapFactory.decodeStream(is);
is.close();
}
catch (IOException e)
{
e.printStackTrace();
}
return image;
}
}
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持億速云。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。