Welcome reprint, Reproduced please indicate the source:
http://blog.csdn.net/johnny901114/article/details/52664112
This article is from: "Bowen's Blog"
On a blog Android development hands-on to teach you to write Butterknife framework (a) We talked about Butterknife is what, butterknife function and function of the introduction and butterknife implementation principle.
This blog is mainly about how to use apt in Android Studio.
First, create a new project, and then a module named processor
When you create a new module, you must choose Java Library otherwise you will not find the abstractprocessor in the back.
Add the following configuration to the Build.gralde in the app and processor folders, respectively:
compileOptions { sourceCompatibility JavaVersion.VERSION_1_7 targetCompatibility JavaVersion.VERSION_1_7}
Second, the construction of a module called annotation, mainly used to save the project to use the annotation.
Import Java. Lang. Annotation. Retention;Import Java. Lang. Annotation. Target;Import static Java. Lang. Annotation. ElementType. FIELD;Import static Java. Lang. Annotation. Retentionpolicy. CLASS;@Retention (CLASS) @Target (FIELD) public @interface bindview {int value ();}
Third, add annotations to the new Mainactivity field as follows:
publicclass MainActivity extends AppCompatActivity { @BindView(R.id.text_view) TextView textView; @BindView(R.id.view) TextView view; @Override protectedvoidonCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); }}
III. Create a new butterknifeprocessor inheritance under the processor module
AbstractProcessor.
@SupportedAnnotationTypes("Com.chiclaim.processor.annotation.BindView")@SupportedSourceVersion(sourceversion.release_7) Public class butterknifeprocessor extends abstractprocessor { @Override Public Boolean Process(set<? extends typeelement> annotations, roundenvironment roundenv) {StringBuilder Builder =NewStringBuilder (). Append ("Package com.chiclaim.processor.generated;\n\n"). Append ("public class Generatedclass {\ n \ nthe")//Open Class. Append ("\tpublic String getMessage () {\ n")//Open method. Append ("\t\treturn \" ");//For each javax.lang.model.element.Element annotated with the Customannotation for(Element Element:roundEnv.getElementsAnnotatedWith (Bindview.class)) {String ObjectType = Element.getsimplename (). toString ();// This was appending to the return statementBuilder.append (ObjectType). Append ("says hello!\\n"); } builder.append (" \"; \ n ")//End return. Append ("\t}\n")//Close Method. Append ("}\n");//Close class Try{//write the fileJavafileobject Source = Processingenv.getfiler (). Createsourcefile ("Com.chiclaim.processor.generated.GeneratedClass"); Writer writer = Source.openwriter (); Writer.write (Builder.tostring ()); Writer.flush (); Writer.close (); }Catch(IOException e) {//Note:calling e.printstacktrace () would print IO errors //That occur from the file already existing after its first run, this is normal}return true; }}
The parameters in the @SupportedAnnotationTypes (...) are the annotations we need to deal with.
Iv. under the Processor module master Directory
resourcesDirectory
Then create META-INF a new directory, then create a new file and create META-INF a new services one, with javax.annotation.processing.Processor the contents of the newly created Butterknifeprocessor qualified name:
com.chiclaim.butterknife.processor.ButterKnifeProcessor
Of course, you can also create so many folders, only need to add Google Autoservice, which will automatically complete the above actions.
@SupportedSourceVersion(SourceVersion.RELEASE_7)@AutoService(Processor.class)//AutoService自动生成文件(in processor.jar): META-INF/services/javax.annotation.processing.Processorclass ButterKnifeProcessor extends AbstractProcessor
Five, add android-apt support
In the global build.gradle add apt support, com.neenbedankt.gradle.plugins:android-apt:1.8 as follows:
buildscript { repositories { jcenter() } dependencies { ‘com.android.tools.build:gradle:2.2.0‘ ‘com.neenbedankt.gradle.plugins:android-apt:1.8‘ not place your application dependencies here; they belong inmodule build.gradle files }}ext { sourceCompatibilityVersion = JavaVersion.VERSION_1_7 targetCompatibilityVersion = JavaVersion.VERSION_1_7}allprojects { repositories { jcenter() }}task clean(type: Delete) { delete rootProject.buildDir}
Add the Apply plugin to the Build.gradle of the app module as shown below:
‘com.android.application‘‘com.neenbedankt.android-apt‘
Vi. adding dependencies between module
dependencies {Compile filetree (include: [' *.jar '], dir:' Libs ') Androidtestcompile (' com.android.support.test.espresso:espresso-core:2.2.2 ', {ExcludeGroup:' Com.android.support ', module:' Support-annotations '}) Compile' com.android.support:appcompat-v7:24.2.1 'Testcompile' junit:junit:4.12 'Compile Project (': annotation ') Compile project (':p rocessor ') Compile project (': Butterknife ')}//Copy the jar generated by processor module to the app Libs directoryTask Processortask (type:exec) {CommandLine ' CP ','. /processor/build/libs/processor.jar ',' libs/'}//build processor Generation Processor.jarProcessortask.dependson (':p rocessor:build ') Prebuild.dependson (Processortask)
As shown in the following:
Code is generated in the app module's build directory, such as:
publicclass GeneratedClass { publicgetMessage() { return"button says hello!\nimageView says hello!\ntextView says hello!\nview says hello!\n"; }}
Thus, the introduction of apt in Android Studio is complete.
Specifically, you can view the GitHub code: Https://github.com/chiclaim/study-butterknife
The next article describes how to implement the Butterknife injection initialization view feature.
Android Development Hands-on teaches you to write Butterknife Framework (ii)