1. 程式人生 > >Butterknife 8.4.0的一些問題

Butterknife 8.4.0的一些問題

寫在前面:

website
github

在github上butterknife的star有11000+
為啥有這麼多人用這個外掛
兩點:
1、自動化
2、有人更新和維護

GRADLE

根目錄的build.gradle
也就是project級

buildscript {
  repositories {
    mavenCentral()
   }
  dependencies {
    classpath 'com.neenbedankt.gradle.plugins:android-apt:1.8'
  }
}

module級別

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

基本的注入我想大部分人都知道

ButterKnife.bind(this)
這裡可以是View,Activity等等

還支援Android annotations的幾個註解

@Optional 可選
@Nullable 可能為空

在8.4.0中最大的改動可能就是使用R2代替R檔案
我覺得這個可能是為了自動生成R檔案經常出現問題的解決方案
應該是和Android Studio中的instant run有衝突

變數的注入

@BindView
TextView textView;

@BindString(R.string.title) 
String title;

@BindDrawable(R.drawable.graphic) 
Drawable graphic;

@BindColor(R.color.red) 
int red;

@BindDimen(R.dimen.spacer) Float spacer; // int (for pixel size) or float (for exact value) field

上面來自於官網

可以修改View的屬性
An Android Property can also be used with the apply method.

ButterKnife.apply(nameViews, View.ALPHA, 0.0f);

onclick事件

//單View的寫法
@OnClick(R.id.submit)
public void submit(View view) {
  // TODO submit data to server...
}

//也可以不寫View引數
@OnClick(R.id.submit)
public void submit() {
  // TODO submit data to server...
}

//也可以將引數進行強轉
@OnClick(R.id.submit)
public void sayHi(Button button) {
  button.setText("Hello!");
}

//也可以是一個數組,這裡批量注入
@OnClick({ R.id.door1, R.id.door2, R.id.door3 })
public void pickDoor(DoorView door) {
  if (door.hasPrizeBehind()) {
    Toast.makeText(this, "You win!", LENGTH_SHORT).show();
  } else {
    Toast.makeText(this, "Try again", LENGTH_SHORT).show();
  }
}

這個暫時沒有試驗,稍後試驗

Custom views can bind to their own listeners by not specifying an ID.
public class FancyButton extends Button {
  @OnClick
  public void onClick() {
    // TODO do something!
  }
}

一些特殊的點選事件

@OnItemSelected(R.id.list_view)
void onItemSelected(int position) {
  // TODO ...
}

@OnItemSelected(value = R.id.maybe_missing, callback = NOTHING_SELECTED)
void onNothingSelected() {
  // TODO ...
}

官網還有一個bouns,看起來是省去了強轉,可以用在dialog等地方

BONUS

Also included are findById methods which simplify code that still has to find views on a View, Activity, or Dialog. It uses generics to infer the return type and automatically performs the cast.

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

Add a static import for ButterKnife.findById and enjoy even more fun.

android studio中有外掛哦
搜尋Butterknife
預設快捷鍵是alt+insert 然後選Butterknife那個
當然有一個ctrl+shift+B的快捷鍵,應該是和其他的有衝突了

暫時先這樣