简单的安卓IOC,免去findViewById

在我们开发android项目的时候,findViewById是使用最频繁且最无技术含量的代码,在比较复杂的UI结构里这将是个比较繁琐耗时的操作;那么我们有没有什么比较好的方法来规避这个操作呢?答案当时是肯定的,例如目前的框架thinkAndroid,可以通过注解的方式来完成UI控件的IOC操作。

这里小弟利用JAVA的反射技术写了一个简单且方便的IOC小程序,下面来给大家介绍一下:

1、android中所有的控件都会有一个ID属性,且这个属性会被注册在R.id中,那么我们就从R.id开始动手脚吧。

private void reflectR(){
	Class rzz = R.id.class;
	for(Field f : rzz.getDeclaredFields()){
                //Data.cacheMap为一个HashMap对象
		Data.cacheMap.put(f.getName(), f);
	}
}

  以上这段代码,我们就把整个项目的R.id全都以key-value的方式存放在了一个全局的HashMap对象中。

2、下面我们看看如何来实现IOC吧。

layout:test.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">

    <RelativeLayout
        android:id="@+id/titleBar"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content">

		<ImageView
		    android:id="@+id/leftbutton"
		    android:layout_width="wrap_content"
		    android:layout_height="wrap_content"
		    android:layout_alignParentLeft="true"
		    android:layout_centerInParent="false"
		    android:layout_centerVertical="true"
		    android:layout_gravity="left"
		    android:src="@drawable/back" />

        <TextView
            android:id="@+id/title"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />

        <ImageView
            android:id="@+id/rightbutton"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />

    </RelativeLayout>

    <LinearLayout
        android:id="@+id/tmp1"
        android:layout_below="@id/titleBar"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <LinearLayout
            android:id="@+id/hj"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:orientation="vertical">
	    <LinearLayout
		android:id="@+id/line1"
		android:layout_width="fill_parent"
                android:layout_height="5dp"/>
        </LinearLayout>
        <LinearLayout
            android:id="@+id/by"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:orientation="vertical">
		<LinearLayout
		 android:id="@+id/line2"
		android:layout_width="fill_parent"
                android:layout_height="5dp"/>
        </LinearLayout>
    </LinearLayout>

    <LinearLayout
        android:id="@+id/tmp2"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_below="@id/tmp1"
        android:orientation="horizontal" >

    </LinearLayout>

    <ListView
        android:id="@+id/listView"
        android:layout_height="fill_parent"
        android:layout_width="fill_parent"
        android:layout_below="@id/tmp2">
    </ListView>
</RelativeLayout>

  

public class Test extends Activity {
        //控件变量的定义名称,必须与layout中的Id一致
	private LinearLayout hj,by,line1,line2;
	private ListView listView;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(this.getLayout());

                //开始IOC自动注入控件
                this.iocElement();

                //下借来你就可以直接使用控件了,并不需要findViewById
	}

	protected int getLayout() {
		return R.layout.test;
	}

        /**
	 * 对符合自动注入规范的控件进行注入
	 * 该方法的实现采取的Java反射原理
	 * 免除了繁琐重复的findViewById(...)操作
	 * @throws Exception
	 */
	private void iocElement() throws Exception{
		Class clzz = this.getClass();
		Field[] fields = clzz.getDeclaredFields();
		for(Field f : fields){
			int v = r(d+f.getName());
			if(v!=0){
				Object obj = this.findViewById(v);
				if(obj!=null){
					f.setAccessible(true);
					f.set(this,obj);
				}
			}
		}
	}

        /**
	 * 在HashMap中判断R.id中是否有该变量,有则返回改ID
	 * @param fieldName
	 * @return
	 * @throws Exception
	 */
	private static int r(String fieldName) throws Exception{
		if(Data.cacheMap.get(fieldName)!=null){
			Field f = (Field)Data.cacheMap.get(fieldName);
			return f.getInt(null);
		}else{
			return 0;
		}
	}
}

  

很简单的IOC程序,希望能为大家的android代码带来一点点方便!

以下是本人的QQ邮箱,希望可以和IT同僚互相交流,也希望能为有需求的朋友解决困难,

邮箱:[email protected]

时间: 2024-08-10 17:08:40

简单的安卓IOC,免去findViewById的相关文章

简单的Spring Ioc

控制反转(Inversion of Control,Ioc),也被称为依赖注入(Dependency Injection,DI),是面向对象的一种设计理念,用来降低程序代码之间的耦合度. 首先要考虑什么是依赖.依赖,在代码中一般是指通过局部变量.方法参数.返回值等建立的对于其他对象的调用关系.例如,A类的方法中,实例化了B类的对象并调用其方法已完成特定的功能,我们就说A类依赖于B类 ---------------------------正文---------------------------

Spring容器的简单实现(IOC原理)

引言:容器是什么?什么是容器?Spring容器又是啥东西?我给Spring容器一个对象名字,为啥能给我创建一个对象呢? 一.容器是装东西的,就像你家的水缸,你吃饭的碗等等. java中能作为容器的有很多,例如Map,List,数组.....还有好多 二.Spring 容器的核心就是一个Map集合(可能不是很准确,见谅!) Map<String, Object> 这个容器里根据key-value存放了好多键值对.假如你给一个String的key,就能获得相应的Object的对象,各位大佬,对Sp

简单实现安卓app自动更新功能

一般的安卓app都有自动更新功能,实现app的更新,以让用户体验新版本的功能,这里也是项目中用到的,今天就来总结一下,代码应该有点多,还请耐心点哈. 安卓应用实现自动更新比较简单,这里跟大家介绍下: 第一步 服务器端: 服务端提供一个借口,或者网址,我这里就用的服务器是tomcat,这里提供一个网址如下: //也就是一个json数据接口 public static final String UPDATE_URL = "http://192.168.1.103:8080/update.json&q

超简单,安卓模拟器手动root

本文转载自:http://quantoubao.blog.163.com/blog/static/2083211702013870501987/ 安装Android SDK安卓模拟器的方法很简单,网上大把,傻瓜式的.不过对其root的方法,网上的版本就不那么好使了.网上的方法从方向性来说是没错的,就是细节没给讲清楚,或者讲错,或者没提到这样root方式对高低不同版本API的区别,导致不少人跟着所谓教程去做都root失败. 我这里以Android4.0.4(API15)为蓝本讲讲适合高版API的A

写了一个简单可用的IOC

根据<架构探险从零开始写javaweb框架>内容写的一个简单的 IOC 学习记录    只说明了主要的类,从上到下执行的流程,需要分清主次,无法每个类都说明,只是把整个主线流程说清楚,避免陷入细节中.学习过程最大的收获,框架也是人写的,没学过感觉很神秘高端.现在看来大概率是,未知往往觉得是高不可攀.http://naotu.baidu.com/file/6c3da879a4495b6bd369f71dcb726f05?token=ed8c0d49d4ee7bbd 原文地址:https://ww

Winfrom 简单的安卓手机屏幕获取和安卓简单操作

为啥我要做这个东西了,是因为经常要用投影演示app ,现在有很多这样的软件可以把手机界面投到电脑上 ,但都要安装,比如说360的手机助手,我又讨厌安装,于是就自己捣鼓了下 做了这个东西, 实现了以下简单功能   1.屏幕获取(因为是截图方式获取的,所以有点卡顿) 2.实现点击功能,并在点击的时候出现一个手势图标,方便用户观看 3.实现简单的滑动功能 4.实现在界面上画图功能 5.实现拖拽安装apk功能 操作说明:鼠标左边 模拟手机点击,中键停止/开始刷新界面(画图的时候不能刷新),右键去掉画图内

Spring.Net 简单实例-01(IOC)

1.话不多说看操作.新建"Windows窗体应用程序" 2:通过配置文件创建IOC容器 首先引入安装包 3:定义一个接口(更好的体现封装性,当然也可以直接使用类) 定义一个类,实现接口 4:配置App.config文件 <?xml version="1.0" encoding="utf-8" ?> <configuration> <configSections> <sectionGroup name=&q

简单的安卓应用授权认证(JNI)

最近一直在做公司的一个安卓开发框架,含so库,接近尾声了,领导提出一个需求,要求使用这个框架的开发者必须有我们的授权才可以,但是对方发布的应用后又不能被此授权限制--要不然所有的应用都来要授权那就麻烦了. 分析: 既然是限制开发者,那么就必须要区分debug版本和release版本,也就是框架的授权限制功能只对debug版本有效,而对release版本无效:然后就是需要一个调试设备的一个唯一ID,这样授权码是绑定在固定的设备的,只要有新的调试设备就需要新的授权码,一般公司里也就是十几个设备吧,这

简单的安卓文件搜索

今天在做的时候需要从大文件开始 搜索各个小文件夹中的图片. 那么就可以使用很简单的递归(效率的问题暂时没怎么考虑). private ArrayList<String> readnewlist(String path) { File file = new File(path); File []files = file.listFiles(); for(int i = 0;i < files.length;i++) { if(files[i].isDirectory()) { String