android使用butterknife InjectView和BindView

Butter Knife 是一個專注於 Android 系統 View 的注入框架,
讓你從煩人的 findViewById 中解脫出來。同時還支持 View 的一些事件處理函數。
butterknife地址:https://github.com/JakeWharton/butterknife
以下介紹兩種實現button的方法

老版本方法(InjectView)

在app目錄下的build.gradle中添加如下依賴

dependencies {  
    compile 'com.jakewharton:butterknife:6.0.0'  
}  

在activity中添加按鍵

public class SimpleActivity extends Activity {  
    @InjectView(R.id.hello)  
    Button hello;  
    @Override  
    protected void onCreate(Bundle savedInstanceState) {  
        super.onCreate(savedInstanceState);  
        setContentView(R.layout.simple_activity);  
        ButterKnife.inject(this);  
      }    
    // hello的點擊事件  
    @OnClick(R.id.hello)  
    void sayHello() {  
        Toast.makeText(this, "Hello, views!", LENGTH_SHORT).show();  
    }  

新版本使用方法(bindView)

在module-level的build.gradle中添加如下依賴

apply plugin: 'android-apt'
dependencies {
  compile 'com.jakewharton:butterknife:8.0.1'
  apt 'com.jakewharton:butterknife-compiler:8.0.1'
}

在project-level的build.gradle中添加如下依賴

dependencies {
  classpath 'com.neenbedankt.gradle.plugins:android-apt:1.8'
  }

在activity中的使用方法

public class SimpleActivity extends Activity {
  @BindView(R.id.hello) Button hello;
  @OnClick(R.id.hello) 
  public void sayHello() {
    Toast.makeText(this, "Hello, views!", LENGTH_SHORT).show();
  }  
  @Override protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.simple_activity);
    ButterKnife.bind(this);
  }
}
發佈了31 篇原創文章 · 獲贊 4 · 訪問量 3萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章