ButterKnife官方教程的翻譯(本人手工翻譯,就當自己理解一遍)

介紹

使用之前的說明

一定要在Gradle添加依賴!!

dependencies {
  compile 'com.jakewharton:butterknife:8.4.0'
      annotationProcessor 'com.jakewharton:butterknife-compiler:8.4.0'        //這條千萬不能忘記!!
}

使用@BindView注釋的屬性 和 View的ID,butterknife可以自動的把代碼中的View和布局文件中的View綁定起來

class ExampleActivity extends Activity {
  @BindView(R.id.title) TextView title;
  @BindView(R.id.subtitle) TextView subtitle;
  @BindView(R.id.footer) TextView footer;

  @Override public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.simple_activity);
    ButterKnife.bind(this);
    // TODO Use fields...
  }
}

不同于緩慢的反射,代碼被生成用來查找View,你可以在debug中查看使用bind方法相當于下面的代碼:

public void bind(ExampleActivity activity) {
  activity.subtitle = (android.widget.TextView) activity.findViewById(2130968578);
  activity.footer = (android.widget.TextView) activity.findViewById(2130968579);
  activity.title = (android.widget.TextView) activity.findViewById(2130968577);
}

資源文件綁定

使用 @BindBool, @BindColor, @BindDimen, @BindDrawable, @BindInt, @BindString 來綁定在XML文件中定義的各種資源文件到變量中

class ExampleActivity extends Activity {
  @BindString(R.string.title) String title;
  @BindDrawable(R.drawable.graphic) Drawable graphic;
  @BindColor(R.color.red) int red; // int or ColorStateList field
  @BindDimen(R.dimen.spacer) Float spacer; // int (for pixel size) or float (for exact value) field
  // ...
}

在沒有Activity的情況下綁定

你可以執行綁定操作在任何對象中,只需要傳入View的Root即可

public class FancyFragment extends Fragment {
  @BindView(R.id.button1) Button button1;
  @BindView(R.id.button2) Button button2;

  @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fancy_fragment, container, false);
    ButterKnife.bind(this, view);
    // TODO Use fields...
    return view;
  }
}

在Adapter的ViewHolder中的另一種簡單的用法

public class MyAdapter extends BaseAdapter {
  @Override public View getView(int position, View view, ViewGroup parent) {
    ViewHolder holder;
    if (view != null) {
      holder = (ViewHolder) view.getTag();
    } else {
      view = inflater.inflate(R.layout.whatever, parent, false);
      holder = new ViewHolder(view);
      view.setTag(holder);
    }

    holder.name.setText("John Doe");
    // etc...

    return view;
  }

  static class ViewHolder {
    @BindView(R.id.title) TextView name;
    @BindView(R.id.job_title) TextView jobTitle;

    public ViewHolder(View view) {
      ButterKnife.bind(this, view);
    }
  }
}

你也可以去參照這個用法的具體實現的樣例(在github上可以下載)

其他提供的API:
  • 使用activity當做根View可以綁定任意對象,如果你使用MVC的設計模式,你可以使用 ButterKnife.bind(this, activity) 來綁定你的controller對象
  • 使用 ButterKnife.bind(this) 可以把一個View的子View和成員變量綁定在一起. 如果你使用<merge>標簽在布局文件中,并且inflate在一個自定義View的構造方法里,你可以在執行完inflate方法后立即使用使用 ButterKnife.bind(this).或者在自定義View的onFinishInflate()回調中使用這個方法

VIEW LISTS

你還可以把不同的view放入一個List或者一個數組中

@BindViews({ R.id.first_name, R.id.middle_name, R.id.last_name })
List<EditText> nameViews;

apply方法可以一次綁定一個list或者數組中的所有view

ButterKnife.apply(nameViews, DISABLE);      //第二個參數是一個Action對象
ButterKnife.apply(nameViews, ENABLED, false);   //第二個參數是一個Setter對象,第三個參數是一個泛型(是setter用來給view設置值的)

上面兩個方法,可以簡單的為每個View初始化一個想要的值

static final ButterKnife.Action<View> DISABLE = new ButterKnife.Action<View>() {
  @Override public void apply(View view, int index) {   //view ---> 具體的view,index ---> view在list中的位置
    view.setEnabled(false);
  }
};
static final ButterKnife.Setter<View, Boolean> ENABLED = new ButterKnife.Setter<View, Boolean>() {
  @Override public void set(View view, Boolean value, int index) {  //第二個參數是個泛型,可以是任意數據類型,不一定是boolean類型,只是官方舉例給了個boolean類型
    view.setEnabled(value);
  }
};

對指定的系統屬性依然可以使用apply方法:

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

監聽器綁定

監聽器也可以被自動的設置

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

所有的監聽器方法的參數都是可選的

@OnClick(R.id.submit)
public void submit() {
  // TODO submit data to server...
}

定義一個具體的類型,它會被自動的轉換

@OnClick(R.id.submit)
public void sayHi(Button button) {
  button.setText("Hello!");
}

指定的多個View如果是一系列通用的事件,ID可以在一起綁定:

@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();
  }
}

自定義View可以綁定自己的監聽器(listener)而不用具體的ID

public class FancyButton extends Button {
  @OnClick
  public void onClick() {
    // TODO do something!
  }
}

BINDING RESET (重置綁定??)

Fragment和Activity相比有不同的生命周期.

現在有個需求:綁定一個Fragment在他的onCreateView()方法中,且在onDestroyView()把引用設置為null時.

你在使用bind()方法的時候,ButterKnife返回一個UnBinder的實例,可以在合適的生命周期中調用unBind方法.

public class FancyFragment extends Fragment {
  @BindView(R.id.button1) Button button1;
  @BindView(R.id.button2) Button button2;
  private Unbinder unbinder;

  @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fancy_fragment, container, false);
    unbinder = ButterKnife.bind(this, view);
    // TODO Use fields...
    return view;
  }

  @Override public void onDestroyView() {
    super.onDestroyView();
    unbinder.unbind();
  }
}

OPTIONAL BINDINGS

默認情況下,@bind和listener綁定均是必須的. 如果目標view沒有被找到會拋出一個異常

為了防止這種情況且創建可選的綁定,在成員變量上需要加上@Nullable,在方法體上加上@Optional .這樣view不存在的時候不會拋出異常

注意:任何名字為@Nullable的注解都可以用在成員變量上, 不推薦使用 Android's "support-annotations" library中的@Nullable注解.

@Nullable @BindView(R.id.might_not_be_there) TextView mightNotBeThere;

@Optional @OnClick(R.id.maybe_missing) void onMaybeMissingClicked() {
  // TODO ...
}

MULTI-METHOD LISTENERS //有多個回調的listener

Method annotations whose corresponding listener has multiple callbacks can be used to bind to any one of them. Each annotation has a default callback that it binds to. Specify an alternate using the callback parameter. //原文

方法的注釋,如果關聯的listener有多個回調函數,則可以指定綁定任意一個回調函數.每個方法注釋都有個默認的回調函數

(比如OnItemSelectedListener中的onItemSelected()就是默認的)

要指定綁定某個回調函數,需要在callback參數中指定(指定的是個枚舉類型)

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

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

BONUS

同時還有簡化的findById方法,實際上是封裝了findViewById()方法,當你在某些地方還是需要使用findViewById方法的地方的時候使用,比如使用在View,Activity,或者Dialog上. 這個方法使用泛型來自動返回對應的View類型

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);

Download

GRADLE

compile 'com.jakewharton:butterknife: (insert latest version)'
annotationProcessor 'com.jakewharton:butterknife-compiler: (insert latest version)'

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

推薦閱讀更多精彩內容