今天开发安卓程序的时候发现如果界面一复杂,要findvVewById的控件就越多,程序员需要不断的复制粘贴,以前也听说有注解的方法可以简化,本人没有过多研究。
我自己写了一个小小的工具类,只需要程序员创建一个简单的属性文件,就能一件获得处理后的代码。
如图:FindViewTools就是该工具类,findview.properties是属性配置文件。
findview.properties:
parent=activity
aa=TextView
bb=ImageView
每个属性文件都有一个parent,代表父亲容器的名字
除了parent
等号左边是对象名,等号右边是类名
下面是FindViewTools:
package 文本处理器;
import java.io.IOException;
import java.io.InputStream;
import java.util.Enumeration;
import java.util.Properties;
/**
* 用于安卓的findView频繁操作 例子:aaa=TextView TextView aaa =
*
* @author wei
*
*/
public class FindViewTools {
public static void main(String[] args) throws IOException {
InputStream in = FindViewTools.class.getClassLoader()
.getResourceAsStream("文本处理器/findview.properties");
Properties properties = new Properties();
properties.load(in);
//拿到名字集合
Enumeration<?> names = properties.propertyNames();
String parent = properties.getProperty("parent");
if(parent==null)
parent = "";
else
parent = parent + ".";
while (names.hasMoreElements()) {
String key = (String) names.nextElement();
if (key.equals("parent"))
continue;
String value = properties.getProperty(key);
System.out.println(value + " " + key + " = " + parent + "findViewById(R.id." + key + ");");
}
}
}
运行结果:
TextView aa = activity.findViewById(R.id.aa);
ImageView bb = activity.findViewById(R.id.bb);
以前我并没有对类加载器加载属性过多研究,导致不知道属性文件的路径如何写,后来查了查,才知道:从源码角度看是从src开始(不包括src),从字节码角度看是从bin(不包括bin)。
此种方法还有待改进,需要程序员做的事还是很多:
1.程序员还需要将局部对象全都变为域对象
2.程序员需要写配置文件工作量还是很大。
以后我会将此方法进一步改进,求业界大牛多指点指点