本文主要是介绍Android的一个BindView工具的实现,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
对于Android已经有很多Bind View的工具了,大多都是使用了反射和注解的方法。那么如何实现一个简易的代码生成工具呢?其实不难,只要会写代码都可以试试。这些天,我试了一下,并将它做成了工具。代码如下:
package com.example;import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;/*** Created by owant on 2016/8/4.*/
public class BindViewTool {public static String xmlPath = "F:\\MyWorkAS\\NewHome\\app\\src\\main\\res\\layout\\activity_main.xml";//第一个是类型,第二个是名字public static String formatValue = "private {0} {1};";//第一个是变量,第二是类型,第三个是IDpublic static String formatBind = "{0}=({1})findViewById(R.id.{2});";public static void main(String[] arg) {//读取文件try {String path="";path=arg[0];if(path.length()<0){System.out.println("请输入文件路径");return;}BufferedReader bufferedReader = new BufferedReader(new FileReader(new File(path)));StringBuffer context = new StringBuffer();String line;String startLine = "";String endLine = "";while ((line = bufferedReader.readLine()) != null) {if (line.trim().length() > 0) {//进入<if (line.trim().startsWith("<") && !line.trim().startsWith("</")) {startLine = line.trim();}//如果已经进入了<,进行查找Idif (startLine.length() > 0) {if (line.indexOf("android:id=\"@+id/") > 0) {endLine = line.trim();context.append(startLine.trim()).append("&&");context.append(endLine.trim()).append("&&");startLine = "";endLine = "";}}}}String contextValue = context.toString();contextValue = contextValue.substring(0, contextValue.length() - "&&".length());String[] splits = contextValue.split("&&");int length = splits.length;List<String> variables = new ArrayList<String>();List<String> binds = new ArrayList<String>();for (int i = 0; i < length; i = i + 2) {String type = splits[i].replace("<", "");if (type.lastIndexOf(".") > 0) {type = type.substring(type.lastIndexOf(".")+1, type.length());}String id = splits[i + 1].substring("android:id=\"@+id/".length(), splits[i + 1].length() - 1);// public static String formatValue = "private {0} {1}";String value = formatValue.replace("{0}", type);value = value.replace("{1}", id);variables.add(value);//public static String formatBind = "{0}=({1})findViewById(R.id.{2})";String bind = formatBind.replace("{0}", id);bind = bind.replace("{1}", type);bind = bind.replace("{2}", id);binds.add(bind);}System.out.println();System.out.println();for (String var : variables) {System.out.println(var);}System.out.println();System.out.println();for (String b : binds) {System.out.println(b);}} catch (FileNotFoundException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}}
}
简单分析一下,就是进行一下的判断,就是在AndroidStudio格式化代码后,进行这样的分析:
1.读取文件的一行;
2.如果是”<”开始的进行获取(A);
3.如果是有”android:id=”@+id/”,进行获取(A)
4.之后进行(A)的出来,如果进入”<”并且下一行时”android:id=”@+id/”,那么就是一个Bind View的必要条件
5.之后整理
最后的工具生成后运行效果如下:
对于如何生存jar大家可以参考我的上一篇文章进行操作。
下载路径 http://download.csdn.net/detail/u012131702/9597057
这篇关于Android的一个BindView工具的实现的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!