android Activity注解方式获取UI实例 绑定事件
程序员文章站
2022-06-08 09:00:27
...
使用注释方式代替findVIewById 并绑定事件
示例:
package com.wf.test; import com.wf.FindView; import com.wf.R; import com.wf.WfAndroidLibActivity; import com.wf.R.layout; import android.app.Activity; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.Button; public class TestActivity extends WfAndroidLibActivity { @FindView(id=R.id.btn1,click="btn1Click") //标注ID,绑定当前TestActivity的btn1Click方法 private Button btn1; //绑定 TestHandler中的 btn2Click方法 @FindView(id=R.id.btn2,click="btn2Click",className="com.wf.test.TestHandler") private Button btn2; public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); this.setContentView(R.layout.main); btn1.setText("btn1 click"); //测试直接赋值 btn2.setText("btn2 click"); } public void doAction() { Log.d("test", "TestHandler call"); } public void btn1Click(View view){ ((Button)view).setText("click1"); Log.d("careland", "btn1---------click"); } }
package com.wf.test; import com.wf.ViewContext; import android.util.Log; import android.view.View; import android.widget.Button; public class TestHandler{ public void btn2Click(View view) { //获取btn1 Button btn1=(Button) ViewContext.getContext().get("btn1"); Log.d("test", btn1.getText().toString());//获取btn1 的text //获取当前activity TestActivity act=(TestActivity) ViewContext.getContext().getCurrentActivity(); act.doAction(); ((Button)view).setText("click2"); Log.d("careland", "btn2 click"); } }
实现源码:
package com.wf; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Inherited; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Inherited @Documented @Target({ElementType.FIELD}) @Retention(RetentionPolicy.RUNTIME) public @interface FindView { int id(); String touch() default "";//touch事件 String click() default ""; //onclick事件 String dbclick() default ""; String itemclick() default ""; String longclick() default ""; String className() default ""; }
package com.wf; import android.app.Activity; import android.os.Bundle; import android.view.View; import android.view.ViewGroup.LayoutParams; import android.widget.Button; //Activity 基类 注入基类 绑定事件 public class WfAndroidLibActivity extends Activity { /** Called when the activity is first created. */ private String TAG="com.careland.WfAndroidLibActivity"; private Button btn; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); } @Override public void setContentView(View view) { super.setContentView(view); GetElement(); } @Override public void setContentView(int id) { super.setContentView(id); GetElement(); } @Override public void setContentView(View view,LayoutParams param) { super.setContentView(view, param); GetElement(); } /** * 注入属性实例 绑定事件 * **/ protected void GetElement() { ViewContext<WfAndroidLibActivity> viewContext=new ViewContext<WfAndroidLibActivity>(this); ViewContext.setContext(viewContext); viewContext.GetElement(this); } }
package com.wf; import java.lang.reflect.Field; import java.lang.reflect.Proxy; import java.util.HashMap; import java.util.Map; import android.app.Activity; import android.content.Context; import android.util.Log; import android.view.View; import android.widget.AdapterView.OnItemClickListener; //注释处理类 public class ViewContext<T> { private String TAG="com.careland.ViewUtil"; private static ThreadLocal<ViewContext> context=new ThreadLocal<ViewContext>(); private T acitivity; private Map<String,Object> fields;//acitvity 中 所有属性 public ViewContext(T acitivity) { this.acitivity=acitivity; fields=new HashMap<String,Object>(); } //获取当前的Activity public T getCurrentActivity() { return acitivity; } //保存 和获取 当前Activity的成员变量 public Map<String,Object> getFields() { return fields; } public Object get(String key) { return fields.get(key); } public void put(String key,Object value) { fields.put(key, value); } public static boolean notNullOrEmpty(String value) { return value!=null&&(!"".equals(value.trim())); } public static ViewContext getContext() { return context.get(); } public static void setContext(ViewContext ctx) { context.set(ctx); } //解析注释 注入成员变量实例 绑定事件 protected void HandlerAnnotation(Field field,Activity ctx) { FindView fv=field.getAnnotation(FindView.class); if(fv!=null) { int viewId=fv.id(); String className=fv.className(); try { field.setAccessible(true); View viewobj=ctx.findViewById(viewId); field.set(ctx, ctx.findViewById(viewId)); this.put(field.getName(),viewobj);// 保存成员变量到Map String touch=fv.touch(); String click=fv.click(); if(viewobj instanceof View) { View view=(View) viewobj; if(notNullOrEmpty(touch)) { view.setOnTouchListener(new ViewEventHandler(ctx,touch,className)); } if(notNullOrEmpty(click)) { view.setOnClickListener(new ViewEventHandler(ctx,click,className)); } // OnItemClickListener f = (OnItemClickListener) Proxy.newProxyInstance(OnItemClickListener.class.getClassLoader(), // new Class[] { OnItemClickListener.class }, // handler); } } catch (Exception e) { Log.d(TAG, "自动初始化View失败",e); } } } public void GetElement(Activity ctx) { Field[] fields=ctx.getClass().getDeclaredFields(); for(Field field:fields) { this.HandlerAnnotation(field, ctx); } } }
package com.wf; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import android.util.Log; import android.view.MotionEvent; import android.view.View; import android.view.View.OnClickListener; import android.view.View.OnTouchListener; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; //对各种事件的处理 public class ViewEventHandler implements OnClickListener, OnTouchListener,OnItemClickListener { private String TAG="com.wf.ViewHandler"; private Object handler; //当前实例 默认activity private String methodName; //要执行的目标方法 private String handlerClass;//要执行的目标类 public ViewEventHandler(Object handler, String method,String handlerClass) { this.handler=handler; this.methodName=method; this.handlerClass=handlerClass; } public ViewEventHandler(Object handler, String method) { this(handler,method,""); } /*** * touch 处理事件 * */ @Override public boolean onTouch(View v, MotionEvent event) { ReflectMethod method=new ReflectMethod(View.class,MotionEvent.class); return (Boolean) method.invoke(v,event); } /** * click处理事件 * **/ @Override public void onClick(View v) { ReflectMethod method=new ReflectMethod(View.class); method.invoke(v); } /** * 执行itemClick事件 * */ @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { ReflectMethod method=new ReflectMethod(AdapterView.class,View.class,Integer.class,Long.class); method.invoke(parent,view,position,id); } //调用目标方法类 class ReflectMethod { public Object instance; public Method method=null; public ReflectMethod(Class... params) { if(!"".equals(handlerClass)) { this.init(handlerClass, methodName, params); }else { this.init(handler, methodName, params); } } public ReflectMethod(Object instance,Method method) { this.instance=instance; this.method=method; } public Object invoke(Object... params) { try { return method.invoke(instance, params); } catch (Exception e) { Log.e(TAG, ""+method.getName()+" error",e); } return null; } public void init(String className,String methodName,Class... params) { try { Class cls = Class.forName(className); this.instance=cls.newInstance(); this.init(instance,methodName,params); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } public void init(Object instance,String methodName,Class... params) { try { this.instance=instance; this.method=instance.getClass().getDeclaredMethod(methodName,params); } catch (Exception e) { e.printStackTrace(); } } } }
上一篇: PHP数据缓存技术之一_PHP教程
下一篇: rails 页面动态title设置问题