Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

用 Android Layout XML 反推自訂 View 程式碼的工具類

編輯:關於 Android 程式設計

這個工具想解決什麼問題

平時開發我們習慣先把介面在 XML 裡排好,再交給 Android 的 LayoutInflater 去 inflate。但有時候情況剛好相反:排版已經在 XML 裡定稿了,我們卻需要一份純 Java 建立 View 的程式碼——例如想把介面在執行期動態拼裝、想避開 inflate 的效能開銷,或者只是想研究一段排版背後到底呼叫了哪些 API。

手寫這種程式碼非常枯燥:每個控制項都要 new 一次、每一組 layout_width/layout_height 都要包成 LayoutParams、每一個 padding 與 margin 都要換算成 px。下面這個小工具做的事,就是把 res/layout 底下的 XML 檔讀進來,用 DOM 解析後遞迴拜訪每個節點,把屬性一一對應成 Java 的 setter 呼叫,最後吐出一整份可以直接編譯的自訂 View 類別。

工具主體程式碼

整體流程分成四段:先用 DocumentBuilderFactory 取得 DOM 文件,接著由 parseRootElement 產生類別外殼與三個建構子,再由 parseElement 遞迴處理子節點,每個節點交給 getAttr 與 compile 負責翻譯屬性。工具會自動為同類型的控制項編號命名(linearlayout1、textview2……),並把用到的 import 收集起來,最後一併插到檔案開頭。

import java.io.File;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Attr;
import org.w3c.dom.Comment;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

/**
 * @author xiaolei
 */
public class Main {

    static Map<String, Integer> fieldNameMap = new HashMap<String, Integer>();
    private static boolean UseDensityUtil = false;
    public static StringBuilder builder = new StringBuilder();
    public static Set<String> importList = new HashSet<String>();

    public static void main(String[] args) throws Exception {
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        DocumentBuilder db = dbf.newDocumentBuilder();
        Document doc = db.parse(new File("E:\\xiaolei\\EclipseProjects\\測試單點登錄\\res\\layout\\test2.xml"));
        Element root = doc.getDocumentElement();          // 取得根元素節點
        parseRootElement(root);
        builder.append("\n\t}");
        if (UseDensityUtil) {
            writeDp2PX();                                  // 有用到 dp/sp 就補上換算工具
        }
        builder.append("\n}");
        for (String im : importList) {                     // 補上 import
            builder.insert(0, im + "\n");
        }
        System.out.println(builder);
    }

    /** 遞迴處理子節點 */
    public static void parseElement(String parent, Element element) {
        NodeList children = element.getChildNodes();
        String fildName = getAttr(element);
        builder.append("\n\t\t" + parent + ".addView(" + fildName + ");");
        for (int i = 0; i < children.getLength(); i++) {
            Node node = children.item(i);
            short nodeType = node.getNodeType();
            if (nodeType == Node.ELEMENT_NODE) {
                parseElement(fildName, (Element) node);
            } else if (nodeType == Node.TEXT_NODE) {
                builder.append("\n");
            } else if (nodeType == Node.COMMENT_NODE) {
                builder.append("//--");
                Comment comment = (Comment) node;
                builder.append(comment.getData());
            }
        }
    }

    /** 處理根節點,負責產生類別外殼 */
    public static void parseRootElement(Element element) {
        NodeList children = element.getChildNodes();
        getRootAttr(element);
        for (int i = 0; i < children.getLength(); i++) {
            Node node = children.item(i);
            short nodeType = node.getNodeType();
            if (nodeType == Node.ELEMENT_NODE) {
                parseElement("this", (Element) node);
            } else if (nodeType == Node.TEXT_NODE) {
                builder.append("\n");
            } else if (nodeType == Node.COMMENT_NODE) {
                builder.append("//--");
                Comment comment = (Comment) node;
                builder.append(comment.getData());
            }
        }
    }

    /** 讀取單一元素的屬性並翻譯 */
    public static String getAttr(Element element) {
        String tagName = element.getNodeName();
        String fildName = getFieldName(tagName);
        builder.append("\n\t\t" + tagName + " " + fildName + " = new " + tagName + "(context);");
        Map<String, String> atts = new HashMap<String, String>();
        NamedNodeMap map = element.getAttributes();
        if (null != map) {
            for (int i = 0; i < map.getLength(); i++) {
                Attr attr = (Attr) map.item(i);
                atts.put(attr.getName(), attr.getValue());
            }
            compile(tagName, fildName, atts);
        }
        return fildName;
    }

    /** 產生類別宣告與三個建構子 */
    public static void getRootAttr(Element element) {
        String tagName = element.getNodeName();
        String fildName = "this";
        builder.insert(0, "import android.content.Context;\n");
        builder.insert(0, "import android.util.AttributeSet;\n");
        builder.append("\npublic class mView extends " + tagName);
        builder.append("\n{");
        builder.append("\n public mView(Context context)");
        builder.append("\n {");
        builder.append("\n this(context,null);");
        builder.append("\n }");
        builder.append("\n public mView(Context context, AttributeSet attrs)");
        builder.append("\n {");
        builder.append("\n this(context, attrs,0);");
        builder.append("\n }");
        builder.append("\n public mView(Context context, AttributeSet attrs, int defStyle)");
        builder.append("\n {");
        builder.append("\n super(context, attrs, defStyle);");
        builder.append("\n InitUI(context);");
        builder.append("\n }");
        builder.append("\n public void InitUI(Context context)");
        builder.append("\n {");
        Map<String, String> atts = new HashMap<String, String>();
        NamedNodeMap map = element.getAttributes();
        if (null != map) {
            for (int i = 0; i < map.getLength(); i++) {
                Attr attr = (Attr) map.item(i);
                atts.put(attr.getName(), attr.getValue());
            }
            compile(tagName, fildName, atts);
        }
    }

    /** 為控制項取名字,同類型自動加序號 */
    public static String getFieldName(String type) {
        Integer num = fieldNameMap.get(type);
        if (num == null) {
            num = 1;
        } else {
            num++;
        }
        fieldNameMap.put(type, num);
        String s[] = type.split("\\.");
        return (s[s.length - 1] + num).toLowerCase();
    }

    /** 依屬性名稱與類型產生對應程式碼 */
    public static void compile(String type, String fieldname, Map<String, String> atts) {
        String height = atts.get("android:layout_height").toUpperCase();
        String width = atts.get("android:layout_width").toUpperCase();
        String weight = atts.get("android:layout_weight");
        String params = getFieldName("LayoutParams");

        // 尺寸:dp/dip/px 走 DensityUtil,match_parent 與 wrap_content 直接對應 LayoutParams 常數
        if (height.endsWith("DP") || height.endsWith("DIP") || height.endsWith("PX")) {
            height = "DensityUtil.dip2px(context," + getNumFromDemin(height) + ")";
        } else {
            height = "LayoutParams." + height;
        }
        if (width.endsWith("DP") || width.endsWith("DIP") || width.endsWith("PX")) {
            width = "DensityUtil.dip2px(context," + getNumFromDemin(width) + ")";
        } else {
            width = "LayoutParams." + width;
        }
        if (weight == null) {
            builder.append("\n\t\tLayoutParams " + params + " = new LayoutParams(" + width + ", " + height + ");");
        } else {
            builder.append("\n\t\tLayoutParams " + params + " = new LayoutParams(" + width + "," + height + "," + weight + ");");
        }

        String layout_gravity = atts.get("android:layout_gravity");
        if (layout_gravity != null) {
            importList.add("import android.view.Gravity;");
            builder.append("\n\t\t" + params + ".gravity = Gravity." + layout_gravity.toUpperCase() + ";");
        }

        // margin:先處理 layout_margin 統一設定,再處理四邊獨立設定(Left/Start、Top、Right/End、Bottom)
        // ... 這一段與 margin 的處理方式完全相同,這裡省略重複的 append 邏輯 ...

        builder.append("\n\t\t" + fieldname + ".setLayoutParams(" + params + ");");

        // 其餘屬性一律是「有就翻譯、沒有就跳過」的同一套模式:
        //   android:orientation   -> setOrientation(LinearLayout.X)
        //   android:visibility    -> setVisibility(View.X)
        //   android:text / hint   -> setText("...") / setHint("...")
        //   android:gravity       -> setGravity(Gravity.X)
        //   android:textSize      -> setTextSize(DensityUtil.sp2px(...))
        //   android:padding*      -> setPadding(...)(Left/Start、Top、Right/End、Bottom 各自覆蓋)
        //   android:textColor     -> setTextColor(Color.parseColor("..."))
        //   android:numColumns    -> setNumColumns(...)
        //   android:scrollbars    -> setHorizontalScrollBarEnabled / setVerticalScrollBarEnabled
        //   android:alpha、focusable、focusableInTouchMode、minWidth、minHeight、tag ...
    }

    /** 取出純數字,並記錄需要 DensityUtil */
    public static String getNumFromDemin(String demin) {
        UseDensityUtil = true;
        String result = "";
        if (demin.toLowerCase().endsWith("dp") || demin.toLowerCase().endsWith("px")
                || demin.toLowerCase().endsWith("sp")) {
            result = demin.substring(0, demin.length() - 2);
        } else if (demin.toLowerCase().endsWith("dip")) {
            result = demin.substring(0, demin.length() - 3);
        } else {
            result = demin;
        }
        return result;
    }

    /** 輸出 dp/sp 與 px 互轉的靜態內部類 */
    public static void writeDp2PX() {
        builder.append("\n\t/** dp、sp 轉換為 px 的工具類 */");
        builder.append("\n\tpublic static class DensityUtil {");
        builder.append("\n\t public static int px2dip(Context context, float pxValue) {");
        builder.append("\n\t  final float scale = context.getResources().getDisplayMetrics().density;");
        builder.append("\n\t  return (int) (pxValue / scale + 0.5f);");
        builder.append("\n\t }");
        builder.append("\n\t public static int dip2px(Context context, float dipValue) {");
        builder.append("\n\t  final float scale = context.getResources().getDisplayMetrics().density;");
        builder.append("\n\t  return (int) (dipValue * scale + 0.5f);");
        builder.append("\n\t }");
        builder.append("\n\t public static int px2sp(Context context, float pxValue) {");
        builder.append("\n\t  final float fontScale = context.getResources().getDisplayMetrics().scaledDensity;");
        builder.append("\n\t  return (int) (pxValue / fontScale + 0.5f);");
        builder.append("\n\t }");
        builder.append("\n\t public static int sp2px(Context context, float spValue) {");
        builder.append("\n\t  final float fontScale = context.getResources().getDisplayMetrics().scaledDensity;");
        builder.append("\n\t  return (int) (spValue * fontScale + 0.5f);");
        builder.append("\n\t }");
        builder.append("\n\t}");
    }
}

看輸出結果

把 compile() 裡那一長串 if 都寫滿之後,工具吐出的自訂 View 大致長這樣。每個控制項都是「建立物件 → 產生 LayoutParams → 設定 LayoutParams → 套用其他屬性 → 加入父容器」的固定五步:

import android.view.View;
import android.widget.LinearLayout;
import android.view.Gravity;
import android.graphics.Color;
import android.util.AttributeSet;
import android.content.Context;

public class mView extends LinearLayout {

    public mView(Context context) { this(context, null); }

    public mView(Context context, AttributeSet attrs) { this(context, attrs, 0); }

    public mView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        InitUI(context);
    }

    public void InitUI(Context context) {
        LayoutParams layoutparams1 = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
        this.setLayoutParams(layoutparams1);
        this.setOrientation(LinearLayout.VERTICAL);

        FrameLayout framelayout1 = new FrameLayout(context);
        LayoutParams layoutparams2 = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
        framelayout1.setLayoutParams(layoutparams2);
        this.addView(framelayout1);

        LinearLayout linearlayout2 = new LinearLayout(context);
        LayoutParams layoutparams4 = new LayoutParams(LayoutParams.MATCH_PARENT, DensityUtil.dip2px(context, 48));
        linearlayout2.setLayoutParams(layoutparams4);
        linearlayout2.setOrientation(LinearLayout.HORIZONTAL);
        linearlayout2.setGravity(Gravity.CENTER_VERTICAL);
        linearlayout1.addView(linearlayout2);

        TextView textview1 = new TextView(context);
        LayoutParams layoutparams5 = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT);
        textview1.setLayoutParams(layoutparams5);
        textview1.setText("←");
        textview1.setGravity(Gravity.CENTER_VERTICAL);
        textview1.setPadding(DensityUtil.dip2px(context, 15), DensityUtil.dip2px(context, 0),
                DensityUtil.dip2px(context, 15), DensityUtil.dip2px(context, 0));
        linearlayout2.addView(textview1);

        GridView gridview1 = new GridView(context);
        LayoutParams layoutparams10 = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
        gridview1.setLayoutParams(layoutparams10);
        gridview1.setNumColumns(7);
        gridview1.setHorizontalScrollBarEnabled(false);
        gridview1.setVerticalScrollBarEnabled(false);
        linearlayout1.addView(gridview1);

        // ... 其餘 month_layout、year_layout、goto_today 等節點同理展開 ...

        TextView textview11 = new TextView(context);
        LayoutParams layoutparams25 = new LayoutParams(LayoutParams.MATCH_PARENT, DensityUtil.dip2px(context, 48));
        textview11.setLayoutParams(layoutparams25);
        textview11.setText("今日");
        textview11.setGravity(Gravity.CENTER);
        this.addView(textview11);
    }

    /** dp、sp 轉換為 px 的工具類 */
    public static class DensityUtil { /* dip2px / px2dip / sp2px / px2sp */ }
}

被解析的 Layout XML

這份輸出的來源就是下面這段日曆選擇器的排版,可以看到 XML 裡的 layout_weight="1"、visibility="gone"、numColumns="7" 都被正確翻成 Java 呼叫了:

<!--?xml version="1.0" encoding="utf-8"?-->
<linearlayout android:layout_height="wrap_content" android:layout_width="wrap_content"
    android:orientation="vertical"
    xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:tools="https://schemas.android.com/tools">

    <framelayout android:layout_height="wrap_content" android:layout_width="match_parent">
        <linearlayout android:id="@+id/show_layout" android:layout_height="wrap_content"
            android:layout_width="match_parent" android:orientation="vertical" android:visibility="visible">
            <linearlayout android:gravity="center_vertical" android:layout_height="48dp"
                android:layout_width="match_parent" android:orientation="horizontal">
                <textview android:id="@+id/porvMonth" android:text="←" ... />
                <linearlayout android:gravity="center" android:layout_height="match_parent"
                    android:layout_weight="1" android:layout_width="0dp" android:orientation="horizontal">
                    <textview android:id="@+id/month" android:text="九月" ... />
                    <textview android:id="@+id/year" android:text="1994" ... />
                </linearlayout>
                <textview android:id="@+id/nextMonth" android:text="→" ... />
            </linearlayout>
            <gridview android:id="@+id/gridview" android:numcolumns="7" android:scrollbars="none" ... />
        </linearlayout>
        <linearlayout android:id="@+id/month_layout" android:visibility="gone" ... />
        <linearlayout android:id="@+id/year_layout" android:visibility="gone" ... />
    </framelayout>

    <textview android:id="@+id/goto_today" android:layout_height="48dp"
        android:layout_width="match_parent" android:gravity="center" android:text="今日" />
</linearlayout>

原始碼預覽

產生的程式碼怎麼用

把 mView 放進專案後,XML 裡只要留一行標籤就好,剩下的排版全靠 InitUI() 在執行期完成:

<!--?xml version="1.0" encoding="utf-8"?-->
<linearlayout android:layout_height="match_parent" android:layout_width="match_parent"
    android:orientation="vertical"
    xmlns:android="https://schemas.android.com/apk/res/android">
    <com.example.point.testlogin.mview
        android:layout_height="match_parent"
        android:layout_width="match_parent">
    </com.example.point.testlogin.mview>
</linearlayout>

自訂控制項預覽

思路小結與可以再加強的地方

這個工具的核心價值不在程式碼本身,而在它把「XML 屬性 → Java API」的對照關係攤開來給你看一次。真的拿來日常使用,還有幾處值得補強:

一是 getFieldName 用 HashMap 記數的方式在多執行緒下不安全,單次執行沒問題但不宜當成元件庫;二是 style 屬性(style="@style/xxx")與 ?attr 引用沒有處理,遇到正規專案的 styleable 就會漏掉;三是 android:id="@+id/..." 目前被直接忽略,實務上通常要改成 setId(R.id.xxx) 才拿得到控制項;四是自訂命名空間屬性完全沒有對應的翻譯規則。把這幾點補上,它就能從「一次性腳本」變成真正好用的日常工具。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved