Android注解框架ButterKnife8.x详解


ButterKnife

前言

Butterknife——相信多同学都知道,这是一个注解框架,一般在绑定View的时候使用。不得不说,这个框架"有毒",用了就上瘾,连写个Demo都要去导这个库。
想必大多数同学都用过ButterKnife,可能你会说“不就是代替了findViewById()吗?”。我想说,确实不只是有findViewById()这个功能。不得不承认,在这之前,我对ButterKnife的使用,也只停留在绑定视图和点击事件上。

介绍

ButterKnife我已经用了好一段时间了,它除了方便,还是方便。ButterKnife为我们简化了很多代码,具体有的作用,可以下面的例子来了解。

看看官方的介绍:

Field and method binding for Android views which uses annotation processing to generate boilerplate code for you
使用注解生成模块代码,用于把一些字段和方法绑定到 Android 的 View。

优势

  • 强大的View绑定和Click事件等处理功能,简化代码,提升开发效率
  • 运行时不会影响APP效率,使用配置方便
  • 代码清晰,可读性强

申明

可能有些人对ButterKnife有一些误解,认为ButterKnife是通过反射来实现的。其实不然,相比缓慢的反射机制,ButterKnife用的APT(Annotation Processing Tool)编译时解析技术。动态生成绑定事件或者控件的java代码,然后在运行的时候,直接调用bind方法完成绑定,因此你不必担心注解的性能问题。骚年,放心去用吧。

使用

啰嗦了半天,终于说到正题了~~

依赖

Project的build.gradle文件中:

buildscript {
  repositories {
    mavenCentral()
     }
  dependencies {
    classpath 'com.jakewharton:butterknife-gradle-plugin:8.4.0'
    }
}

Module的build.gradle文件中:

apply plugin: 'com.android.library'
apply plugin: 'com.jakewharton.butterknife'
dependencies { 
    compile 'com.jakewharton:butterknife:8.4.0' 
    annotationProcessor 'com.jakewharton:butterknife-compiler:8.4.0'
}
单个View——@BindView
  • 在Activity中使用
    例:绑定布局中的TextViewButtonEditText

    • 没有ButterKnife时,各种烦人的findViewById()和强转:
      TextView textView = (TextView) findViewById(R.id.text_view);
      Button button = (Button) findViewById(R.id.button);
      EditText editText = (EditText) findViewById(R.id.edit_text);
    • 使用ButterKnife后:
      先绑定对应的View
      @BindView(R.id.text_view)
      TextView mTextView;
      @BindView(R.id.button)
      Button mButton;
      @BindView(R.id.edit_text)
      EditText mEditText;
      然后在onCreate()setContentView()下添加ButterKnife.bind(this);
      @Override
      protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);
      }
      然后这些View就可以随心所欲的使用了,方便吧!

      注意:这里的View不可以是privatestatic类型

  • 在Fragment、Adapter中使用
    除了Activity,我们常用的场景还有Fragment,以及Adapter。用法跟在Activity中大致相似。

    • Fragment中
      例:绑定布局中的TextViewButtonEditText
      public class MainFragment extends Fragment {
      @BindView(R.id.text_view)
      TextView mTextView;
      @BindView(R.id.button)
      Button mButton;
      @BindView(R.id.edit_text)
      EditText mEditText;
      @Override
      public View onCreateView(LayoutInflater inflater,ViewGroup container, Bundle savedInstanceState) {
          View rootView = inflater.inflate(R.layout.frag_main, container, false);
          ButterKnife.bind(this, rootView);//这里有些不同
          return rootView;
        }
      }

      提示:如果我们需要在某个时候将Fragment中的view设置为null,这时候需要用到Unbinder。在onCreateView中使用bind方法时,会返回一个Unbinder对象,该对象中有的unbinder方法,可以将Fragment中的View设置为null

    • Adapter中
      例:绑定布局中的TextViewButton
      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);
          }
           //....
          return view;
        }
        static class ViewHolder {
          @BindView(R.id.text_view) TextView mTextView;
          @BindView(R.id.button) Button mButton;;
          public ViewHolder(View view) {
             ButterKnife.bind(this, view);
          }
        }
      }

      提示:在使用BindView方法的时候,如果目标View没有找的的话,会抛出异常。如果不想受到这个异常,可以使用@Nullable

      @Nullable @BindView(R.id.text_view)
多个View——@BindViews

使用这种绑定时,你可以使用apply()方法。该函数相当于将在这个列表中每一个元素上进行调用.利用ButterKnife的ActionSetter接口来执行一些简单的操作

  • 例:隐藏指定的View
    先使用List<View>绑定视图
    @BindViews({R.id.text_view, R.id.button, R.id.edit_text})
    List<View> mViews;
    • 使用Action
      final ButterKnife.Action<View> VIEWS_GONE = new ButterKnife.Action<View>() {
      @Override
      public void apply(@NonNull View view, int index) {
          view.setVisibility(View.GONE);
      }
      };
      ButterKnife.apply(mViews, VIEWS_GONE);
    • 使用Setter
      final ButterKnife.Setter<View, Boolean> VIEWS_VISIAVLE = new ButterKnife.Setter<View, Boolean>() {
      @Override
      public void set(@NonNull View view, Boolean value, int index) {
          final int IS_VISIAVLE = value ? View.VISIBLE : View.GONE;
          view.setVisibility(IS_VISIAVLE);
      }
      };
      ButterKnife.apply(mViews, VIEWS_VISIAVLE, false);
  • Android属性也可以和apply方法一起使用。
    ButterKnife.apply(nameViews, View.ALPHA, 0.0f);
点击事件——@OnClick

在使用的过程中,除了@BindView,还有@OnClick也是经常用到的。

  • 例:为Button设置点击事件
    @OnClick(R.id.button)
    public void onButtonClick(View view) {
      Toast.makeText(this, "button被点击了", Toast.LENGTH_SHORT).show();
    }
    参数View就是被点击的视图
    如果可以确认View的具体类型,可以这样写。如:已知为Button类型
    @OnClick(R.id.button)
    public void onButtonClick(Button button) {
      Toast.makeText(this, "button被点击了", Toast.LENGTH_SHORT).show();
    }
    如果不需要用到参数View,也可以去掉
    @OnClick(R.id.button)
    public void onButtonClick() {
      Toast.makeText(this, "button被点击了", Toast.LENGTH_SHORT).show();
    }
  • 例:多个点击事件
    @OnClick({R.id.text_view, R.id.button, R.id.edit_text})
    public void onTextviewClick(View view) {
      switch (view.getId()){
          case R.id.text_view:
              Toast.makeText(this, "text_view被点击了", Toast.LENGTH_SHORT).show();
              break;
          case R.id.button:
              Toast.makeText(this, "button被点击了", Toast.LENGTH_SHORT).show();
              break;
          case R.id.edit_text:
              Toast.makeText(this, "edit_text被点击了", Toast.LENGTH_SHORT).show();
              break;
      }
    }
  • 例:item的点击事件
    @BindView(R.id.list_view)
    ListView mListView;
    private String[] strs = {"1","2","3","4","5"};
    mListView.setAdapter(new ArrayAdapter<String>(getContext(), 
          android.R.layout.simple_list_item_1, strs));
    @OnItemClick(R.id.list_view)
    void onItemClick(int potion) {
      Toast.makeText(getContext(), "点击了:" + potion, Toast.LENGTH_SHORT).show();
    }
    @OnItemClick,当然也有@OnItemLongClick。具体的用法我就不写了...
  • 自定义View绑定事件监听时无需ID
    public class FancyButton extends Button {
      @OnClick
      public void onClick() {
        // TODO do something!
      }
    }

    注意:
    1、方法名可以随便取
    2、跟View一样,方法也不能为privatestatic类型

资源绑定

可以利用@BindBool,@BindColor,@BindDimen,@BindDrawable,@BindInt,@BindString来绑定资源,如下

class MainActivity 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
  // ...
}
findById方法

如果在某些场景下,你真的需要用到findViewById()方法。不用担心,ButterKnife中包含了findById()方法来替代findViewById(),可以在View,Activity, 或Dialog中使用

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

Zelezny插件

如果你是像我一样高(lan)效(duo)的程序员,一点都不想写这些东西。那么福利来了,那就是Zelezny插件(Android Studio)。只要在布局中写上'id',所有绑定的代码自动生成。厉害了

  • 安装插件


    安装插件
  • 使用
    然后只要右键布局id上,选择Generate,点击Generate Butterknife Injections,该插件会从对应的布局中查找有id属性的View,然后会出现在对应的选择页面。点击Confirm即可。


    操作

最后的提示

几点有关ButterKnife的提示,使用时避免踩坑。

  • Activity: ButterKnife.bind(this);
    必须在setContentView();之后,且父类bind绑定后,子类不需要再bind
  • Fragment :ButterKnife.bind(this, mRootView);
  • 属性布局不能用private 或static 修饰,否则会报错
  • setContentView()不能通过注解实现。
  • ButterKnife已经更新到版本8.x了,以前的版本中叫做@InjectView,7.x中叫@Bind,而现在改用叫@BindView

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Vincent(朱志强)

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值