Android implements dynamic conversion of external xml files to view layout

First use as to create an xml layout file, then use aapt or as to compile it to generate a binary xml file and store it on the server. The app downloads the compiled xml file, calls the system parser XmlResourceParser to parse it, and finally LayoutInflater converts it into a View.

/**
     * 二进制xml转view
     *
     * @param context
     * @param binXmlFile
     * @return
     */
    private View xmlFileToView(Context context, File binXmlFile) {
        FileInputStream in = null;
        try {
            in = new FileInputStream(binXmlFile);
            byte[] buf = new byte[(int) binXmlFile.length()];
            int len = in.read(buf);
            if (len != binXmlFile.length()) return null;
            Class cXmlBlock = Class.forName("android.content.res.XmlBlock");
            Constructor constructor = cXmlBlock.getConstructor(byte[].class);
            constructor.setAccessible(true);
            Object xmlBlock = constructor.newInstance(buf);
            Method newParser = cXmlBlock.getDeclaredMethod("newParser");
            newParser.setAccessible(true);
            XmlResourceParser parser = (XmlResourceParser) newParser.invoke(xmlBlock);
            return LayoutInflater.from(context).inflate(parser, null);
        } catch (Exception e) {
            Log.e("xmlFileToView", e.toString());
        } finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

Guess you like

Origin blog.csdn.net/zzmzzff/article/details/123414201