Android ButterKnife註解框架使用

  這段時間學習了下ButterKnife註解框架,學習的不是特別深入,但是基礎也差不多了,在此記錄總結一下。

  ButterKnife是一個Android View注入的庫,主要是註解的使用,可以減少很多代碼的書寫,使代碼結構更加簡潔和整齊。ButterKnife可以避免findViewById的調用,Android開發的人都知道在Android初始化控件對象的時候要不斷地調用findviewById,有多少控件就需要調用多少次,而使用ButterKnife可以省去findViewById的調用,不僅如此還可以省去監聽事件的冗長代碼,只需要一個註解就可以完成。下面我們來看看ButterKnife到底是如何使用的。

一、如何引入ButterKnife?

1. 首先是在Project的gradle中添加依賴:

dependencies {
        //butterknife的導入
        classpath 'com.neenbedankt.gradle.plugins:android-apt:1.8'
}

2. 在app的gradle中添加如下:
在gradle中添加:

apply plugin: 'android-apt'

在gradle的dependencies中添加:

dependencies {
    compile 'com.jakewharton:butterknife:8.4.0'
    apt 'com.jakewharton:butterknife-compiler:8.4.0'
}

3. rebuild就完成了。

這裏關於Project和app中build.gradle的區別可以參考這篇文章:Android Project和app中兩個build.gradle配置的區別

二、如何使用?

注意:button 的修飾類型不能是:private 或者 static 。 否則會報錯:錯誤: @BindView fields must not be private or static. (com.zyj.wifi.ButterknifeActivity.button1)

(一)、View的綁定

1. 控件id的註解:@BindView()

@BindView(R.id.toolbar)
public Toolbar toolbar;

然後再Activity的onCreate()中調用:

ButterKnife.bind( this ) ;

2. 多個控件id 註解: @BindViews()

    @BindViews({ R.id.button1  , R.id.button2 ,  R.id.button3 })
    public List<Button> buttonList ;

然後再Activity的onCreate()中調用:

ButterKnife.bind( this ) ;

3. 綁定其他View中的控件
Butter Knife提供了bind的幾個重載,只要傳入跟佈局,便可以在任何對象中使用註解綁定。調用ButterKnife.bind(view. this);方法。但是一般調用 Unbinder unbinder=ButterKnife.bind(view, this)方法之後需要在調用 unbinder.unbind()解綁。
所以一般在activity中調用之後再綁定其他的view中的控件時我都會使用(四)中的方法。

(二)、資源的綁定

<resources>
    <string name="hello">Hello</string>
    <string-array name="array">
        <item>hello</item>
        <item>hello</item>
        <item>hello</item>
        <item>hello</item>
    </string-array>
</resources>

1. @BindString() :綁定string 字符串

    @BindString(R.string.hello)
    public String hello;

然後再Activity的onCreate中調用:

ButterKnife.bind( this ) ;

2. @BindArray() : 綁定string裏面array數組

    @BindArray(R.array.array)  //綁定string裏面array數組
    String [] array;

然後再Activity的onCreate()中調用:

ButterKnife.bind( this ) ;

3. @BindBitmap( ) : 綁定Bitmap 資源

    @BindBitmap(R.mipmap.ic_launcher)
    public Bitmap bitmap;

然後再Activity的onCreate()中調用:

ButterKnife.bind( this ) ;

6. 其他資源
綁定BindColor(),BindDimen(),BindDrawable(),BindInt()等都是同樣的方法,(1). 綁定資源。 (2).調用ButterKnife.bind()方法。

(三)、事件的綁定

1. 綁定OnClick方法

    @OnClick(R.id.login_activity_button_login)
    public void clickLogin() {
    }

然後再Activity的onCreate()中調用:

ButterKnife.bind( this ) ;

如果綁定多個id的話,用“,”逗號隔開。

(四)、其他

Butter Knife提供了一個findViewById的簡化代碼:findById,用這個方法可以在View、Activity和Dialog中找到想要View,而且,該方法使用的泛型來對返回值進行轉換,也就是說,你可以省去findViewById前面的強制轉換了。

View view = LayoutInflater.from(context).inflate(R.layout.thing, null);
TextView firstName = ButterKnife.findById(view, R.id.first_name);

ButterKnife.bind的調用可以被放在任何你想調用findViewById的地方。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章