There are several common ways to bind a button in Android, you can set the ID for the button in the layout file, and then get the instance of the button object in Mainactivity through the Findviewbyid method, and then bind the event by setonclicklistener the button , as shown below:
// 1. Get control btn = (Button) Findviewbyid (r.id.button1); // 2. Bind event Btn.setonclicklistener (new Onclicklistener () { @Override public void OnClick (View v) { callphone (); } });
You can also set the OnClick property directly for the button in the layout file, and then implement the method in Mainactivity (the actual application is less than the application, this article is mainly a way for the opportunity, so no longer repeat the basic grammar format).
When there are many buttons in an application that need to bind events, and even a lot of buttons need to bind the event with some commonality, we can refer to some popular tool classes, using the reflection principle and annotations in Java to write a simple tool class, help us do the above work, so that the code looks more concise, Improve productivity.
First, let's briefly introduce some of the violent reflexes and annotations that this article will use.
The reflection mechanism, which is any class in Java, can map its properties, construction methods, methods and annotations into method, Constructor, Field, annotation class by acquiring its bytecode, and then manipulate it. The so-called violent reflex is the use of obj.setaccessible (true) to force private members to be used for some members of a class that are declared private.
Annotations in Java annotation, usually our common JDK provided by some of the notes are not unfamiliar, such as @override (hint to rewrite the parent class method, if not a rewrite will be an error); @Deprecated (suppress outdated warnings) , @SuppressWarnings (suppression warning), in short, annotations are annotations that are read to the JVM. This article will use custom annotations and probably write a small example to illustrate the use of custom annotations:
Package Com.yuki.vu; 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 myinject { int value (); }
@interface is the symbolic declaration of the annotation class (note that class members can only be of the following types: Basic data type, class type, enum type
Meta-Annotations: |
@Retention: The specified annotation scope |
Value: |
Retentionpolicy.source Java Source Range visible |
Retentionpolicy.class. CLASS byte code visible |
Retentionpolicy.runtime is visible when running. |
|
@Target: Represents a defined annotation decoration range (properties, methods, classes) |
Elementtype.type: Annotation Decoration class |
Elementtype.method: Annotation Retouching method |
elementtype.filed: Annotation Decoration Properties |
The above is just a brief introduction to reflection and annotations, please use the details to find additional information. Let's start by writing our gadget with the following code:
Myviewutils.java file
PackageCom.yuki.vu;ImportJava.lang.reflect.Field;ImportJava.lang.reflect.Method;Importandroid.app.Activity;ImportAndroid.view.View;ImportAndroid.view.View.OnClickListener; Public classMyviewutils { Public Static voidInjectFinalactivity activity) { //Reflection Propertiesfield[] Declaredfields =Activity.getclass (). Getdeclaredfields (); for(inti = 0; i < declaredfields.length; i++) {Field field=Declaredfields[i]; Field.setaccessible (true); myinject annotation= Field.getannotation (myinject.class); if(annotation!=NULL) { intID =Annotation.value (); View View=Activity.findviewbyid (ID); Try{Field.set (activity, view); } Catch(Exception e) {e.printstacktrace (); } } } //Reflection Methodmethod[] Declaredmethods =Activity.getclass (). Getdeclaredmethods (); for(inti = 0; i < declaredmethods.length; i++) { FinalMethod method =Declaredmethods[i]; Method.setaccessible (true); Myclick annotation= Method.getannotation (Myclick.class); if(annotation!=NULL) { int[] Value =Annotation.value (); for(intj:value) { intID =J; FinalView BTN =Activity.findviewbyid (ID); Btn.setonclicklistener (NewOnclicklistener () {@Override Public voidOnClick (View v) {Try{Method.invoke (activity, BTN); } Catch(Exception e) {e.printstacktrace (); } } }); } } } }}
Myinject.java file:
Package Com.yuki.vu; 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 myinject { int value (); }
Myclick.java file:
Package Com.yuki.vu; Import Java.lang.annotation.ElementType; Import java.lang.annotation.Retention; Import Java.lang.annotation.RetentionPolicy; Import Java.lang.annotation.Target, @Retention (retentionpolicy.runtime) @Target (Elementtype.method) public @Interface myclick { int[] Value ();}
In mastering the use of reflection and annotations on the basis of understanding the above code should not be difficult (where the code is not clear where you can comment on the message ha ^.^), you can import the three files from the source file directly into the project, you can also package them into a jar file, later used in the import libs, the following:
PackageCom.yuki.vu;ImportAndroid.os.Bundle;Importandroid.app.Activity;ImportAndroid.util.Log;ImportAndroid.view.View;ImportAndroid.widget.Button;ImportAndroid.widget.EditText;ImportAndroid.widget.TextView;ImportAndroid.widget.Toast; Public classMainactivityextendsActivity {@MyInject (r.id.tv)PrivateTextView TV; @MyInject (r.id.et)PrivateEditText et; @MyInject (R.ID.BTN1)PrivateButton btn1; @MyInject (R.ID.BTN2)PrivateButton btn2; @MyInject (R.ID.BTN3)PrivateButton Btn3; @Overrideprotected voidonCreate (Bundle savedinstancestate) {Super. OnCreate (savedinstancestate); Setcontentview (R.layout.activity_main); Myviewutils.inject ( This); LOG.D ("Tag", "" "+Btn1.gettext ()); } @MyClick ({r.id.btn1, r.id.btn2, r.id.btn3}) Public voidSubmit (View view) {Toast.maketext ( This, ((Button) view). GetText (), Toast.length_short). Show (); }}
The above is the mainactivity code. As you can see, in the case of using the tool class, we first get each button control with an ID through the @myinject annotation, then bind the event to each button by Myclick method, and finally pass a sentence myviewutils.inject (this) in the OnCreate method. To complete the binding of the button to the event.
In fact, the above content is also from the famous tool class Xutils reference, you can find these powerful tools in GitHub and other Web site source code and detailed instructions for use, so this article only for our own writing tools to do a small example, for reference only, Welcome to Exchange ~
Android custom tool classes get buttons and bind events (using violent reflections and annotations)