Butter Knife ——Android视图的字段(Field)和方法(Method)绑定

来源:互联网 发布:淘宝店主货源 编辑:程序博客网 时间:2024/05/14 23:52

ButterKnife:注解框架

  • ButterKnife注解框架
    • 介绍
    • 下载
    • License

原文出处
GitHub地址

> 介绍


  • 绑定视图

使用@bindview,根据视图ID在布局中自动匹配对应的视图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...  }}

生成代码来执行视图查找替代了慢映射.。结合绑定视图你可以查看并调试生成代码。

上述示例的生成代码大致相当于以下代码:

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 绑定预先定义的资源,根据资源ID(可以是自定义的类型)绑定到对应的字段。

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的绑定

还可以通过自己提供的根视图来绑定任意对象视图

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里面的视图,简化适配器里面的视图保持模式。

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

你可以在上面提供的实例中看到动作的实现

你可以将 ButterKnife.bind 应用到任何你使用 findViewById 的地方

其他提供绑定的APIs:

  • Activity作为根视图你可以绑定任意的对象。如果你采用MVC模式你能够用 ButterKnife.bind(this, activity) 来绑定控制器来使用它的Activity。

  • 使用 ButterKnife.bind(this) 绑定视图的子对象。如果你在布局中有使用< merge >标签以及有使用自定义视图也能够直接调用,另外,在XML使用的自定义视图可以在 onFinishInflate() 回调中使用


  • 多个view(视图列表)

你能够对多个view进行分组进一个list或者数组

@BindViews({ R.id.first_name, R.id.middle_name, R.id.last_name })List<EditText> nameViews;The apply method allows you to act on all the views in a list at once.ButterKnife.apply(nameViews, DISABLE);ButterKnife.apply(nameViews, ENABLED, false);Action and Setter interfaces allow specifying simple behavior.static final ButterKnife.Action<View> DISABLE = new ButterKnife.Action<View>() {  @Override public void apply(View view, int index) {    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) {    view.setEnabled(value);  }};

Android视图的属性也可以用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!");}

一个绑定命令绑定多个视图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();  }}

自定义视图可以绑定他们自己的监听器而不使用ID

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

  • 绑定复位(binding reset)
    Fragments的生命周期跟Activity不尽相同,
    在Fragment的onCreateView生命周期里绑定view,
    在Fragment的onDestroyView生命周期里面将view置为null。
    当你绑定这个Fragment的时候Butter Knife会返回一个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();  }}

  • 可选的绑定

默认情况下,不管是使用绑定视图还是绑定监听,当目标视图找不到的时候会引发异常
为了制止这种情况,你可以创建一个可选的绑定,绑定视图的时候添加一个 @Nullable 注解或者在绑定监听的时候添加一个@Optional注解
注:@Nullable可以用于任何字段,这是来自Android官方的support-annotations库里面的注解,Android官方也鼓励大家使用的注解。

@Nullable @BindView(R.id.might_not_be_there) TextView mightNotBeThere;@Optional @OnClick(R.id.maybe_missing) void onMaybeMissingClicked() {  // TODO ...}

  • 多个方法监听器

方法注解对应的监听器可能有多个回调,可以绑定他们中的任何一个,每一个方法注解在绑定时有他默认的回调,可以根据参数来绑定哪一个回调。

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

  • 福利
    也能够使用findById方法在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);

添加一个静态的包 ButterKnife.findById的引用 就可以享受更多的乐趣

import ButterKnife.findById;//这里包名不完整,不可直接使用

> 下载

  • GRADLE
compile 'com.jakewharton:butterknife:(insert latest version)'//替换成最新的版本号annotationProcessor 'com.jakewharton:butterknife-compiler:(insert latest version)'//同样需要替换成最新的版本号

> License

Copyright 2013 Jake Wharton

Licensed under the Apache License, Version 2.0 (the “License”);
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an “AS IS” BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

0 0
原创粉丝点击