2016-11-2

BufferKnife的集成和基本使用

1.使用:在build.gradle里加入

  compile 'com.jakewharton:butterknife:8.4.0
  'apt 'com.jakewharton:butterknife-compiler:8.4.0'

加入之后發現報錯,錯誤大致如下:

Gradle DSL method not found: 'apt()'
....

解決:需要引入一個apt的插件,app的項目目錄下的build.gradle文件里,加入一句話
apply plugin: 'android-apt'

apply plugin: 'com.android.application'
apply plugin: 'android-apt'

同時在app的根目錄下的build.gradle的目錄里也添加這么一句話
classpath 'com.neenbedankt.gradle.plugins:android-apt:1.8'

dependencies { 
     classpath 'com.android.tools.build:gradle:2.1.0'  
     classpath 'com.neenbedankt.gradle.plugins:android-apt:1.8'    

  // NOTE: Do not place your application dependencies here; they belong    
  // in the         individual module build.gradle files
 }

最后重新編譯下就可以了。

2.使用場景

  • 簡化 findViewById
    在Activity中使用:
@BindView(R.id.fab) FloatingActionButton fab;
@Override
protected void onCreate(Bundle savedInstanceState) {   
       super.onCreate(savedInstanceState); 
       setContentView(R.layout.activity_scrolling);  
      //初始化   
      ButterKnife.bind(this);
}

在Fragment中使用稍微有點不同:
初始化的時候要用2個參數的構造 方法

ButterKnife.bind(this,getView());

當bindind 在onCreateView方法中的時候,要在onDestroyView中把這些views 變為null,ButterKnife提供一個 unbind 方法去做這個事情

unbinder = ButterKnife.bind(this,getView());

@Override
public void onDestroyView() {    
       super.onDestroyView(); 
       unbinder.unbind();
}
  • view holder綁定
    class MyViewHolder { 
    @BindView(R.id.title) private TextView title;
    public MyViewHolder(View view){      
             ButterKnife.bind(this,view);   
    

}}
初始化一組:

@BindViews({R.id.name1,R.id.name2,R.id.name3})
List<EditText> names;

個人感覺這個功能并不是特別方便,所以不多加介紹了,還可以設置View的一些屬性(透明度等)

ButterKnife.apply(names,View.ALPHA,1.0f);
  • 點擊事件中
@OnClick(R.id.fab)
public void onClick(){   
       //do something
}
  • 默認情況下 @Bind 和 監聽都是必須的,如果id沒找到就會拋出一個異常,為了避免這種情況發生,我們可以添加一個 @Nullable在字段上 或者 @Optional 注解在方法上。

    這個 @Nullable注解 來自(http://tools.android.com/tech-docs/support-annotations).

@Nullable
@BindView(R.id.fab)
FloatingActionButton fab;

@Optional
@OnClick(R.id.fab)
public void onClick(){ 
   //do something
}
  • MULTI-METHOD LISTENERS 就是listview item點擊這種類型的綁定,可以這么來寫
@OnItemSelected(R.id.list_view)
void onItemSelected(int position) {
     // TODO ...
}

  @OnItemSelected(value = R.id.maybe_missing, callback = NOTHING_SELECTED)
  void onNothingSelected() {
       // TODO ...
  }
  • BONUS
    同樣還是 findById 方法 也可以用更簡單的方法,在這個View,Activity 或者Dialog,自動返回類型,不用強轉了。
View view = LayoutInflater.from(context).inflate(R.layout.thing, null);
TextView firstName = ButterKnife.findById(view, R.id.first_name);

編寫參考 http://jakewharton.github.io/butterknife/ 官方說明還有文檔

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容