本文主要是介绍使用butterknife注解,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
懒人模式开启
今天了解下butterknife注解框架使用,省去了findViewById,onClick代码的拼写
git上的开源项目链接如下:
https://github.com/JakeWharton/butterknife/
我们就进行一些配置吧:
在Module中build.gradle进行如下配置
apply plugin: 'com.neenbedankt.android-apt'
dependencies {compile 'com.jakewharton:butterknife:8.2.1'apt 'com.jakewharton:butterknife-compiler:8.2.1'
}
我们需要在Project的build.gradle中配置如下代码:
dependencies {classpath 'com.neenbedankt.gradle.plugins:android-apt:1.8'}
主界面就2个TextView控件
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"xmlns:tools="http://schemas.android.com/tools"android:layout_width="match_parent"android:layout_height="match_parent"android:orientation="vertical"tools:context="com.example.administrator.myapplication.MainActivity"><TextView
android:id="@+id/textView1"android:background="#ccc"android:gravity="center"android:layout_width="fill_parent"android:layout_height="50dp"android:text="Hello World!1" /><TextView
android:id="@+id/textView2"android:background="#999"android:gravity="center"android:layout_width="fill_parent"android:layout_height="50dp"android:text="Hello World!2" />
</LinearLayout>
在MainActivity中
package com.example.administrator.myapplication;import android.app.Activity;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;import org.w3c.dom.Text;import java.util.ArrayList;import butterknife.BindColor;
import butterknife.BindString;
import butterknife.BindView;
import butterknife.BindViews;
import butterknife.ButterKnife;
import butterknife.OnClick;public class MainActivity extends Activity {@BindView(R.id.textView1) TextView textView1;@BindView(R.id.textView2) TextView textView2;@BindColor(R.color.colorAccent) int color;@BindString(R.string.app_name) String myStr;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);ButterKnife.bind(this);Log.i("MainActivity","color:"+color+",myStr:"+myStr);}@OnClick({R.id.textView1,R.id.textView2})public void myOnClick1(View view){switch (view.getId()){case R.id.textView1:Log.i("MainActivity", "textView1 onclick");break;case R.id.textView2:Log.i("MainActivity", "textView2 onclick");break;}}}
log输出
09-03 18:16:21.719 5437-5437/? I/MainActivity: color:-49023,myStr:My Application
09-03 18:16:36.088 5437-5437/com.example.administrator.myapplication I/MainActivity: textView1 onclick
09-03 18:16:37.300 5437-5437/com.example.administrator.myapplication I/MainActivity: textView2 onclick
这篇关于使用butterknife注解的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!