Come on, let's write an IOC framework for Android !, Androidioc framework

Source: Internet
Author: User

Come on, let's write an IOC framework for Android !, Androidioc framework

Currently, the afinal development framework has been in use for several months. Remember the first time you used annotations to initialize controls and bind events, how excited I was at that time-the code could be written like this! Then, as I continue to learn, I have gradually gained a simple understanding of the IOC framework, annotation reflection, and other things. In the previous article, I briefly introduced the Java reflection mechanism, in today's article, we will complete a simple Demo Based on IOC, so that you can learn a little bit about IOC.

First, what is IOC?

Inversion of Control (IoC) is an important Object-Oriented Programming Law to reduce the coupling of computer programs. It is also the core of a lightweight Spring framework. There are two types of control inversion: Dependency Injection (DI) and Dependency search. Dependency injection is widely used.

What we need to accomplish below is the implementation of dependency injection in Android.

First, let's look at our project structure.


The structure is very simple. It is a base class, a subclass, a custom annotation type, and a layout file.

The specific implementation of the Code is as follows:

First, let's look at the most important base class

BaseActivity. java

Package com. example. iocdemo; import java. lang. reflect. field; import android. app. activity; import android. content. context; import android. view. view; import android. view. view. onClickListener; import android. widget. toast; public class BaseActivity extends Activity {protected Context mContext = this;/*** implement IOC injection ** @ param baseActivity */public void initInjectedView (Object baseActivity) {// obtain all member variables Field [] Fields = baseActivity. getClass (). getDeclaredFields (); if (fields! = Null & fields. length> 0) {// traverse the member variable for (Field field: fields) {try {// suppress permission check field. setAccessible (true); // obtain the comments of member variables. ViewInject viewInject = field. getAnnotation (ViewInject. class); // if the annotation class is not empty, that is, the member variable is declared as if (viewInject! = Null) {// obtain the idint id = viewInject in the comment. id (); // set the field value field. set (this, (Activity) baseActivity ). findViewById (id); // retrieves the instantiated View object from the View field. get (this); // bind the listener event view. setOnClickListener (new OnClickListener () {@ Overridepublic void onClick (View v) {Toast. makeText (mContext, "don't worry! ", Toast. LENGTH_SHORT). show () ;}}}} catch (Exception e) {e. printStackTrace ();}}}}}

In this class, we have completed writing the IOC injection method. The custom annotation type code is as follows:

package com.example.iocdemo;import java.lang.annotation.ElementType;import java.lang.annotation.Retention;import java.lang.annotation.RetentionPolicy;import java.lang.annotation.Target;@Target(ElementType.FIELD)@Retention(RetentionPolicy.RUNTIME)public @interface ViewInject {public int id();}
@ Target (ElementType. FIELD) This code controls the position of the comment as a FIELD or a member variable, because we need to complete the comment of the control and bind it with the time. Therefore, we set it to ElementType. FIELD.

@ Retention is an enum type, which has three values: SOURCE, CLASS, and RUNTIME ..

SOURCE indicates that the Annotation type information will only be stored in the program SOURCE code. If the SOURCE code is compiled, the Annotation data will disappear and will not be stored in the compiled data. class file.

ClASS indicates that the Annotation type information is stored in the program source code and compiled. in the class file, this information is not loaded into the Virtual Machine (JVM) during execution. note that when you do not set a Retention value of the Annotation type, the default value is CLASS.
RUNTIME indicates that information is retained in the source code and compiled. class files. During execution, this information is loaded into the JVM.

Because we need to complete the injection after the JVM loads our class file, we select this attribute.

Now we know how to define a custom annotation type and use code to implement code injection and event binding. Next, let's take a look at our program, how to use it.

Below is the code of our Activity

Package com. example. iocdemo; import android. OS. bundle; import android. widget. button; public class MainActivity extends BaseActivity {// use comments to initialize the control @ ViewInject (id = R. id. btn) Button btn; @ Overrideprotected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. activity_main); // inject initInjectedView (this );}}

The following figure shows the running result.



A container class similar to IOC needs to be designed

A typical simple factory.
Public class Helper <T>
Where T: class, new ()
{
Public T GetInstance (T obj)
{
If (obj! = Null)
{
Return obj;
}
Else
{
Obj = Activator. CreateInstance (typeof (T) as T;
Return obj;
}

}
}
Test:
System. ArgumentException ar = null;
Helper <System. ArgumentException> helper = new Helper <System. ArgumentException> ();
Object iar = helper. GetInstance (ar );

How to write your own javascript framework

You can start with simple encapsulation. For example, you can encapsulate some common methods and other people only need to call them, no matter how you implement them internally. As for the effect, I usually use some jq plug-ins, which is convenient and quick.
It is relatively simple to provide what I wrote. It's just a matter of hands-on experience.
(Function (){
If (! Window. Mr_2_ B ){
Window. Mr_2_ B = {};

}

Function trim (txt ){
Return txt. replace (/(^ \ s *) | (\ s * $)/g ,"");
}
Window. Mr_2_ B .trim = trim;
})();

// Page call (do not forget to introduce)

Mr_2_ B .trim ("hi ");
Mr_2_ B is defined by myself, and there are many implementation methods, which can be used as a reference for the author.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.