美文网首页
ButterKnife官方教程的翻译(本人手工翻译,就当自己理解

ButterKnife官方教程的翻译(本人手工翻译,就当自己理解

作者: 吐痰高手 | 来源:发表于2017-11-08 22:45 被阅读16次

    介绍

    使用之前的说明

    一定要在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)'

    相关文章

      网友评论

          本文标题:ButterKnife官方教程的翻译(本人手工翻译,就当自己理解

          本文链接:https://www.haomeiwen.com/subject/ibsumxtx.html