根据XML文件的id自动写java文件的声明方法和findViewById方法

前端之家收集整理的这篇文章主要介绍了根据XML文件的id自动写java文件的声明方法和findViewById方法前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

Android开发中经常遇到大量的控件和按钮,在xml中定义后,为了控制控件还需要在java文件中通过id找到xml中定义的控件,给编程增加了很大的工作量

下面的代码是在之前另一个程序上改的,本来想使用jni,用C语言操作文件的,后来感觉java效率也是足够的,就直接java了,jni没用上。

xml解析找到id:

写入代码

读写文件,找到文件工具类:

/**
 * @FileName AutoUtil.java
 * @Package com.example.jni.utils
 * -------------------------------------
 * @function Please write description of function
 * @Date 2015-8-8 下午6:03:24
 * -------------------------------------
 * Copyright (c) 2015,顾博君 All Rights Reserved.
 */
package com.bobby.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

/**
 * 
 * @ClassName AutoUtil
 * @author 顾博君
 * @Date 2015-8-10 下午1:48:42
 * @Function
 */
public class AutoUtil {

	/**
	 * 读取xml子元素的递归方法
	 * 
	 * @param root
	 * @param strArray
	 */
	private void readChildElementsAndReturn(List<Element> root,String[] strArray) {
		for (Element child : root) {
			// 未知属性名情况下
			List<Attribute> attributeList = child.attributes();
			for (Attribute attr : attributeList) {
				if (attr.getName().equals("id")) {
					// 0id字符串 1是声明函数 2找id语句 3onclick声明语句
					strArray[Constant.INDEX_VIEW_ID] += child.getName() + ":"
							+ attr.getValue().substring(5) + "|";
					strArray[Constant.INDEX_ANNOUNCE] += "private "
							+ child.getName() + " "
							+ attr.getValue().substring(5) + ";\n";
					strArray[Constant.INDEX_FINDVIEWBYID] += attr.getValue()
							.substring(5)
							+ "=("
							+ child.getName()
							+ ")findViewById(R.id."
							+ attr.getValue().substring(5) + ");\n";
					strArray[Constant.INDEX_ONCLICK] += attr.getValue()
							.substring(5) + ".setOnClickListener(this);\n";
					strArray[Constant.INDEX_IMPORTWIDGET] += attr.getValue()
							.substring(5)
							+ "import android.widget."
							+ child.getName() + ";\n";
				}
			}
			if (child.hasContent()) {
				readChildElementsAndReturn(child.elements(),strArray);
			}
		}
	}

	/**
	 * 读取xml文件
	 * 
	 * @param xmlUrl
	 * @param str
	 */
	public void readXmlAndReturn(String xmlUrl,String[] str) {
		SAXReader reader = new SAXReader();
		File file = new File(xmlUrl);
		Document document = null;
		try {
			document = reader.read(file);
		} catch (DocumentException e) {
			e.printStackTrace();
		}
		Element root = document.getRootElement();
		List<Element> childElements = root.elements();
		readChildElementsAndReturn(childElements,str);
		str[Constant.INDEX_VIEW_ID] = str[Constant.INDEX_VIEW_ID].substring(0,str[Constant.INDEX_VIEW_ID].length() - 1);// 去掉多余的|
	}

	public void writeJava(String javaUrl,String[] strArray) {
		// 利用正则找到java中关键代码
		String pat_publicClass = "(public\\s+class)(.*)\\{(\\s)*";
		String pat_onCreate = "void(\\s)+onCreate(\\s)*\\(Bundle(\\s)+([0-9a-zA-Z_])+\\)(\\s)*\\{(\\s)*"
				+ // 匹配void onCreate(Bundle savedInstanceState){
				"(super\\.onCreate\\(([0-9a-zA-Z_])+\\);)?(\\s)*" + // 匹配super.onCreate(savedInstanceState);
				"(setContentView\\((\\S)+\\)(\\s)*;)?(\\s)*";// setContentView(R.layout.activity_main);
		String pat_Package = "package\\s+(.*)[;](\\s+)";
		Pattern p_publicClass = Pattern.compile(pat_publicClass);// 匹配主类名
		Pattern p_onCreate = Pattern.compile(pat_onCreate);// 匹配onCreate方法
		Pattern p_Package = Pattern.compile(pat_Package);// 匹配包
		Matcher matcher = null;
		Matcher m_Package = null;
		String willBeWrite = strArray[Constant.INDEX_ANNOUNCE];
		FileInputStream fis = null;
		FileOutputStream fos = null;
		try {
			// 读文件
			String fileContent = new String();
			File file = new File(javaUrl);
			fis = new FileInputStream(file);
			byte[] b = new byte[fis.available()];// 新建一个字节数组
			fis.read(b);// 将文件中的内容读取到字节数组中

			String line = new String(b);
			int start = 0;
			// 找package,添加import
			m_Package = p_Package.matcher(line);
			if (m_Package.find()) {
				start = m_Package.end();
				fileContent += line.substring(0,start);
				String[] viewName = strArray[0].split("\\|");
				for (String str : viewName) {
					String[] temp = str.split(":");// 获取名字
					if (fileContent.indexOf(temp[0]) < 0) {// 如果没有重复的
						fileContent += "import android.widget." + temp[0]
								+ "\r\n";
					}
				}
			}
			fileContent += line.substring(start);
			line = fileContent;
			fileContent = "";
			start = 0;
			matcher = p_publicClass.matcher(line);
			if (matcher.find()) {
				start = matcher.end();
				fileContent += line.substring(0,start);
				// 写入 private XXXView xxxid;
				fileContent += willBeWrite;
			}
			fileContent += line.substring(start);
			line = fileContent;
			fileContent = "";
			start = 0;
			matcher = p_onCreate.matcher(line);// 匹配oncreate方法
			while (matcher.find()) {
				start = matcher.end();
				fileContent += line.substring(0,start);
				// 写入 xxxid=(XXXView)findViewById(R.id.xxxid);
				fileContent += strArray[Constant.INDEX_FINDVIEWBYID]
						+ "\r\n";
			}
			fileContent += line.substring(start);
			System.out.println(fileContent);
			// 写文件
			fos = new FileOutputStream(file);
			fos.write(fileContent.getBytes());
		} catch (IOException e) {
			System.out.println("!!!IO异常!!!");
			e.printStackTrace();
		} finally {
			try {
				fis.close();
				fos.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
}

主类:

/**
 * @FileName TestMain.java
 * @Package com.booby.main
 * -------------------------------------
 * @function Please write description of function
 * @Date 2015-8-8 下午7:23:23
 * -------------------------------------
 * Copyright (c) 2015,顾博君 All Rights Reserved.
 */
package com.booby.main;

import com.bobby.util.AutoUtil;
import com.bobby.util.LogUtil;
import com.bobby.util.UrlUtil;

/**
 * 
 * @ClassName TestMain
 * @author 顾博君
 * @Date 2015-8-10 下午1:48:52
 * @Function
 */
public class TestMain {
	static {
		System.loadLibrary("jni//dll");
	}

	public static void main(String[] args) {
		UrlUtil url = new UrlUtil("test");// 工程名
		AutoUtil auto = new AutoUtil();
		LogUtil.isNeedExName = true;
		String xmlUrl = url.getXmlUrl("activity_main");// xml文件名
		String javaUrl = url.getJavaUrl("/com/example/test/MainActivity.java");// java文件路径
		LogUtil.out(xmlUrl);
		LogUtil.out(javaUrl);
		System.out
				.println("-----------------------------------------------------------------------------------");
		String str[] = new String[] { "","","" };// 0id字符串 1是声明函数 2找id语句
														// 3onclick声明语句
		auto.readXmlAndReturn(xmlUrl,str);
		LogUtil.out("\n" + str[0]);
		LogUtil.out("\n" + str[1]);
		LogUtil.out("\n" + str[2]);
		System.out
				.println("-----------------------------------------------------------------------------------");
		auto.writeJava(javaUrl,str);
	}
}


</pre><pre class="java" name="code">
日志类:

/**
 * @FileName LogUtil.java
 * @Package com.bobby.util
 * -------------------------------------
 * @function Please write description of function
 * @Date 2015-7-31 下午4:21:35
 * -------------------------------------
 * Copyright (c) 2015,顾博君 All Rights Reserved.
 */
package com.bobby.util;

/**
 * @ClassName LogUtil
 * @author 顾博君
 * @Date 2015-7-31 下午4:21:35
 * @Function 调试信息工具类
 */
public class LogUtil {
	private static String TAG = "LogUtil";
	public static boolean isNeedExName = false;
	/**
	 * @description 是否是调试模式 ,调试模式下会在控制台打印log信息
	 * */
	public static boolean IsDebug = true;

	/**
	 * Get The Current Function Name
	 * 
	 * @return
	 */
	private static String getFunctionName() {
		StackTraceElement[] sts = Thread.currentThread().getStackTrace();
		if (sts == null) {
			return null;
		}
		for (StackTraceElement st : sts) {
			if (st.isNativeMethod()) {
				continue;
			}
			if (st.getClassName().equals(Thread.class.getName())) {
				continue;
			}
			if (st.getClassName().equals(LogUtil.class.getName())) {
				continue;
			}
			TAG = st.getFileName();
			return "[ Thread:" + Thread.currentThread().getName()
					// + " | FileName:" + st.getFileName()
					+ " | Line:" + st.getLineNumber() + " | Method:"
					+ st.getMethodName() + " ]";
		}
		return null;
	}

	/**
	 * @date 2015-8-7
	 * @param msg
	 *            log信息
	 */
	// public static void V(String msg) {
	// String str = getFunctionName();
	// if (!isNeedExName) {
	// TAG = TAG.substring(0,TAG.lastIndexOf('.'));
	// }
	// v(TAG,str + " - " + msg);
	// }

	/**
	 * @brief System.out.println();信息
	 * @param Context
	 * @param String
	 */
	public static void out(String msg) {
		String str = getFunctionName();
		if (!isNeedExName) {
			TAG = TAG.substring(0,TAG.lastIndexOf('.'));
		}
		out(TAG,str + " - " + msg);
	}

	/**
	 * @brief System.out.println();信息
	 * @param Context
	 * @param String
	 */
	private static void out(String tag,String msg) {
		if (IsDebug) {
			System.out.println(tag + "----" + msg);
		}
	}
}

urlUtil.java:

/**
 * @FileName UrlUtil.java
 * @Package com.bobby.util
 * -------------------------------------
 * @function Please write description of function
 * @Date 2015-8-8 下午7:39:43
 * -------------------------------------
 * Copyright (c) 2015,顾博君 All Rights Reserved.
 */
package com.bobby.util;

/**
 * 
 * @ClassName UrlUtil
 * @author 顾博君
 * @Date 2015-8-10 下午1:49:12
 * @Function
 */
public class UrlUtil {
	private String projectName = null;

	public UrlUtil(String projectName) {
		this.projectName = projectName;
	}

	public String getXmlUrl(String fileName) {
		if (fileName.lastIndexOf('.') < 1)
			fileName += ".xml";
		return getworkspaceUrl() + "\\" + projectName + "\\res\\layout\\"
				+ fileName;
	}

	public String getJavaUrl(String fileName) {
		if (fileName != null) {
			if (fileName.lastIndexOf('.') < 1)
				fileName += ".java";
			if (fileName.length() > 1
					&& (fileName.charAt(0) == '\\' || fileName.charAt(0) == '/'))
				fileName = fileName.substring(1);
		}
		fileName = fileName.replace('/','\\');
		return getworkspaceUrl() + "\\" + projectName + "\\src\\" + fileName;
	}

	public String getworkspaceUrl() {
		String projectRootUrl = System.getProperty("user.dir");
		String workspaceUrl = projectRootUrl.substring(0,projectRootUrl.lastIndexOf('\\'));
		return workspaceUrl;
	}
}

常量:
/**
 * @FileName Constant.java
 * @Package com.bobby.util
 * -------------------------------------
 * @function Please write description of function
 * @Date 2015-8-11 上午10:47:22
 * -------------------------------------
 * Copyright (c) 2015,顾博君 All Rights Reserved.
 */
package com.bobby.util;

/**
 * @ClassName Constant
 * @author 顾博君
 * @Date 2015-8-11 上午10:47:22
 * @Function
 */
public class Constant {
	public static final int INDEX_VIEW_ID = 0;
	public static final int INDEX_ANNOUNCE = 1;
	public static final int INDEX_FINDVIEWBYID = 2;
	public static final int INDEX_ONCLICK = 3;
	public static final int INDEX_IMPORTWIDGET = 4;
}



文件结构:


dom4j下载地址:http://download.csdn.net/detail/gubojun123/8987749
代码下载地址:http://download.csdn.net/detail/gubojun123/8993799
原文链接:https://www.f2er.com/xml/296323.html

猜你在找的XML相关文章