I. Introduction
In Android, you can use findViewById to find the desired View in the layout file. Adding a View to an Activity requires initialization. This is a very tedious task. Of course, Google will find many Android Annotations frameworks. For example, the famous "Android Annotations", such a framework is very complicated and troublesome to use, and there are some bugs. The first use also took a lot of time to study. Maybe you only want to use the Inject View function in the project, or you want to know how this implementation works. This article mainly solves these two problems and implements a simplest ViewInject.
Ii. Principles
The principle is to dynamically set a value for the field after the Activity is loaded by finding the annotation field in the Activity, and then using Java reflection.
1. First, You Need To Know How Java annotations work. If you do not know about them, you can read the relevant documents first. This is a simple answer. First, define our annotation class:
/*** View inect by id ** @ author Lucky **/@ Target (ElementType. FIELD) // indicates the @ Retention (RetentionPolicy. RUNTIME) // indicates the public @ interface ViewInject {int value () default 0 ;}
2. We need to define a BaseActivity to parse the annotation in this class.
/***** @ Author Lucky **/public abstract class BaseActivity extends FragmentActivity {/*** get content view layout id ** @ return */public abstract int getLayoutId (); @ Overrideprotected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (getLayoutId (); autoInjectAllField ();}/*** parse annotation */public void autoInjectAllField () {try {Class
Clazz = this. getClass (); Field [] fields = clazz. getDeclaredFields (); // obtain the Field declared in the Activity for (field: fields) {// check whether this Field has the if (field. isAnnotationPresent (ViewInject. class) {ViewInject inject = field. getAnnotation (ViewInject. class); int id = inject. value (); if (id> 0) {field. setAccessible (true); field. set (this, this. findViewById (id); // set the value for the field we are looking for }}} catch (IllegalAccessException e) {e. printStackTrace ();} catch (IllegalArgumentException e) {e. printStackTrace ();}}}
3. After completing the above steps, the sample code is as follows:
public class TestActivity extends BaseActivity {@ViewInject(R.id.claim_statement)private WebView mWebView;@Overridepublic int getLayoutId() {// TODO Auto-generated method stubreturn R.layout.activity_claim;}}
In this way, you can. Several lines of code can greatly improve work efficiency.
Iii. References
1. http://www.bkjia.com/kf/201405/302998.html