Android advanced tutorial teaches you how to build the IOC framework [ViewInject] (I) and androidviewinject in Android

Source: Internet
Author: User

Android advanced tutorial teaches you how to build the IOC framework [ViewInject] (I) and androidviewinject in Android

Reprinted please indicate the source: bytes]

1. Overview

First, let's boast about IoC. What does Inversion of Control (IoC) mean?

That is, you need to use many member variables in a class. In traditional writing, if you want to use these member variables, you can use new variables ~~

The IoC principle is: NO, we don't need new, so the coupling degree is too high. You configure an xml file to indicate which class and which member variables are used in it, I will help you inject (new) when loading this class;

What are the benefits of doing so?

To answer this question, I can answer another question. Many people ask, is it hierarchical project development, which can be divided into control layer, business layer, and DAO layer. Then each layer requires a package-based interface for sub-deployment and a package-based implementation? Can I use only one implementation package ~ If you understand IoC, you will know the functions of these interfaces. The above is not to say that you don't need new. You just need to declare the member variables + write a configuration file, someone will help you with new. In this case, you can declare all the member variables to be used as interfaces in the class, and then you will find that when the implementation class changes, or switch the implementation class, what do you need to do? You only need to make a simple modification in the configuration file. If you are using a real implementation class, now you need to find all the places where you declare this implementation class and manually modify the class name. If you meet a changing boss, right, huh ~

Of course, many may think that writing a configuration file and a slot is too troublesome. As a result, there is another solution. You have to worry about the configuration file. Use annotations. You can add an annotation to the member variable to be injected, for example, @ Inject. You can't say this word ~~

Of course, with configuration files and annotations, how can we inject them? Actually, it is to turn the string class path into a class. Of course, reflection is on the stage. That said, a long time ago, reflection was very slow. Well, it was a long time ago. Now it is not too slow, of course, it cannot reach the native speed ~~ No reflection, no framework.

If you think that the annotation reflects the high level of Shenma. Let me say: Just Do It, you will find that the annotation is similar to writing a normal JavaBean. What about reflection? The APIs are just a few lines, so never be stunned ~

2. Framework Implementation

Now, the Android IOC framework is mainly used to inject all the controls and layout files. If you have used the xUtils and afinal class frameworks, you must be familiar with them ~

Inject View

Assume that we have 10 views in an Activity.

Traditional Practice: we need to first set the layout file for this Activity, and then put ~

Target practice: add an annotation on the Activity class to help us automatically inject the layout of Liberal Arts; add a line of annotation when declaring the View, and then automatically help us findViewById;

As a result, our target class is like this:

@ContentView(value = R.layout.activity_main)public class MainActivity extends BaseActivity{@ViewInject(R.id.id_btn)private Button mBtn1;@ViewInject(R.id.id_btn02)private Button mBtn2;

3. Encoding
1. Define annotations

First, we need two annotation files:

package com.zhy.ioc.view.annotation;import java.lang.annotation.ElementType;import java.lang.annotation.Retention;import java.lang.annotation.RetentionPolicy;import java.lang.annotation.Target;@Target(ElementType.TYPE)@Retention(RetentionPolicy.RUNTIME)public @interface ContentView{int value();}

ContentView is used in the class and is mainly used to indicate the layout files required for the Activity.

@ContentView(value = R.layout.activity_main)public class MainActivity

package com.zhy.ioc.view.annotation;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{int value();}

Used on member variables to specify the View Id

@ViewInject(R.id.id_btn)private Button mBtn1;

To put it simply, annotation: The Defined keyword @ interface; @ Target indicates where the annotation can be used, possible types: TYPE (class), FIELD (member variable), and possible types:

public enum ElementType {    /**     * Class, interface or enum declaration.     */    TYPE,    /**     * Field declaration.     */    FIELD,    /**     * Method declaration.     */    METHOD,    /**     * Parameter declaration.     */    PARAMETER,    /**     * Constructor declaration.     */    CONSTRUCTOR,    /**     * Local variable declaration.     */    LOCAL_VARIABLE,    /**     * Annotation type declaration.     */    ANNOTATION_TYPE,    /**     * Package declaration.     */    PACKAGE}

These are the enumerated values.

@ Retention: indicates the level at which the annotation information needs to be saved. Here we set it to runtime.

Possible types:

public enum RetentionPolicy {    /**     * Annotation is only available in the source code.     */    SOURCE,    /**     * Annotation is available in the source code and in the class file, but not     * at runtime. This is the default policy.     */    CLASS,    /**     * Annotation is available in the source code, the class file and is     * available at runtime.     */    RUNTIME}

These enumerations ~

2. MainActivity

package com.zhy.zhy_xutils_test;import android.app.Activity;import android.os.Bundle;import android.view.View;import android.view.View.OnClickListener;import android.widget.Button;import android.widget.Toast;import com.zhy.ioc.view.ViewInjectUtils;import com.zhy.ioc.view.annotation.ContentView;import com.zhy.ioc.view.annotation.ViewInject;@ContentView(value = R.layout.activity_main)public class MainActivity extends Activity implements OnClickListener{@ViewInject(R.id.id_btn)private Button mBtn1;@ViewInject(R.id.id_btn02)private Button mBtn2;@Overrideprotected void onCreate(Bundle savedInstanceState){super.onCreate(savedInstanceState);ViewInjectUtils.inject(this);mBtn1.setOnClickListener(this);mBtn2.setOnClickListener(this);}@Overridepublic void onClick(View v){switch (v.getId()){case R.id.id_btn:Toast.makeText(MainActivity.this, "Why do you click me ?",Toast.LENGTH_SHORT).show();break;case R.id.id_btn02:Toast.makeText(MainActivity.this, "I am sleeping !!!",Toast.LENGTH_SHORT).show();break;}}}

The annotations are all written. The core code is ViewInjectUtils. inject (this ~

3. ViewInjectUtils

1. First, inject the code of the main layout file:

/*** Inject the main layout file ** @ param activity */private static void injectContentView (Activity activity) {Class <? Extends Activity> clazz = activity. getClass (); // query whether the ContentView annotation ContentView contentView = clazz. getAnnotation (ContentView. class); if (contentView! = Null) // {int contentViewLayoutId = contentView. value (); try {Method method = clazz. getMethod (METHOD_SET_CONTENTVIEW, int. class); method. setAccessible (true); method. invoke (activity, contentViewLayoutId);} catch (Exception e) {e. printStackTrace ();}}}

Obtain the Class type of the input activity object and determine whether the annotation ContentView is written. If so, read its value and obtain the setContentView method, which is called using invoke;

There is a constant:

private static final String METHOD_SET_CONTENTVIEW = "setContentView";

2. Inject Views

Private static final String METHOD_FIND_VIEW_BY_ID = "findViewById";/*** inject all controls ** @ param activity */private static void injectViews (Activity activity) {Class <? Extends Activity> clazz = activity. getClass (); Field [] fields = clazz. getDeclaredFields (); // traverses all member variables for (Field field: fields) {ViewInject viewInjectAnnotation = field. getAnnotation (ViewInject. class); if (viewInjectAnnotation! = Null) {int viewId = viewInjectAnnotation. value (); if (viewId! =-1) {Log. e ("TAG", viewId + ""); // initialize Viewtry {Method method = clazz. getMethod (METHOD_FIND_VIEW_BY_ID, int. class); Object resView = method. invoke (activity, viewId); field. setAccessible (true); field. set (activity, resView);} catch (Exception e) {e. printStackTrace ();}}}}}
Obtain all declared attributes, traverse them, find the attributes with the ViewInject annotation or their values, call the findViewById method, and set the value to field ~~~

Okay. Just write the two methods into inject.

public static void inject(Activity activity){injectContentView(activity);injectViews(activity);}

This article describes how to build such a framework. The next article will teach you how to inject events and stop writing setXXXListener ~~~


:



Download source code







What are common android design patterns or frameworks? I am talking about the most common SSH frameworks, such as those in j2ee.

There is no framework in android.
Just do it well by following the mvc layering principle. Some open-source libraries such as facebook also have a lot of open-source libraries. You can consider using it.

Familiar with Android Application and framework development. I hope to use the Android system from top to bottom to provide a tutorial on android embedded underlying development.

Baidu liberal arts, Netease video College, Baidu course, Youku, and 51 search on the self-learning network, there should be
Open Courses on various websites
------------------ @ Select a satisfactory answer @------------------
 

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.