ButterKnife8 使用说明

作者: 雨林雨林 | 来源:发表于2016-11-08 19:20 被阅读2166次

    ButterKnife 8

    成员变量和方法的依赖注入框架

    资料

    Github

    官网

    ButterKnife-Zelezny Github
    ButterKnife 插件

    导入

    项目中使用

    • 配置模组的 build.gradle
    dependencies {
        compile 'com.jakewharton:butterknife:8.4.0'
        annotationProcessor 'com.jakewharton:butterknife-compiler:8.4.0'
    }
    

    库中使用

    • 配置项目的 build.gradle
    buildscript {
        repositories {
          mavenCentral()
         }
        dependencies {
          classpath 'com.jakewharton:butterknife-gradle-plugin:8.4.0'
        }
    }
    
    • 配置模组的 build.gradle
    apply plugin: 'com.android.library'
    apply plugin: 'com.jakewharton.butterknife'
    
    • 在注解中使用R2代替R

    基本用法

    初始化

    • Activity 中初始化
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.simple_activity);
        ButterKnife.bind(this);
        // ...
    }
    
    • Fragment 中初始化
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment, container, false);
        ButterKnife.bind(this, view);
        // ...
        return view;
    }
    
    • ViewHolder 中初始化
    static class ViewHolder {
        public ViewHolder(View view) {
            ButterKnife.bind(this, view);
        }
    }
    
    • 注意
      • <merge>标签布局,可在构造器重填充后初始化
      • 在xml中填充自定义View,须在onFinishInflate()中初始化

    View绑定

    @BindView@BindViews

    不能绑定 private、static

    @BindView(R.id.name)
    EditText nameView; // 替代 findViewById
    
    @BindViews({ R.id.first_name, R.id.middle_name, R.id.last_name })
    List<EditText> nameViews;
    

    资源绑定

    @BindString@BindBool@BindInt@BindFloat@BindArray@BindDimen@BindColor@BindBitmap@BindDrawable

    @BindString(R.string.username_error)
    String usernameErrorText;
    
    @BindBool(R.bool.is_tablet)
    boolean isTablet;
    
    @BindInt(R.int.columns)
    int columns;
    
    // 可绑定 float 类型的 dimen 资源
    @BindFloat(R.dimen.image_ratio)
    float imageRatio;
    
    // 可绑定String、int、Text 数组和 android.content.res.TypedArray
    @BindArray(R.array.countries)
    String[] countries;
    
    @BindArray(R.array.phones)
    int[] phones;
    
    @BindArray(R.array.options)
    CharSequence[] options;
    
    @BindArray(R.array.icons)
    TypedArray icons;
    
    // 可绑定 int (像素尺寸), float (具体大小值)
    @BindDimen(R.dimen.horizontal_gap)
    int gapPx;
    
    @BindDimen(R.dimen.horizontal_gap)
    float gap;
    
    // 可绑定 int, ColorStateList
    @BindColor(R.color.background_green)
    int green;
    
    @BindColor(R.color.background_green_selector)
    ColorStateList greenSelector;
    
    @BindBitmap(R.drawable.logo)
    Bitmap logo;
    
    @BindDrawable(R.drawable.placeholder)
    Drawable placeholder;
    
    @BindDrawable(value = R.drawable.placeholder, tint = R.attr.colorAccent)
    Drawable tintedPlaceholder;
    

    监听绑定

    @OnClick@OnLongClick@OnTouch@OnCheckedChanged@OnEditorAction@OnFocusChange@OnTextChanged@OnItemClick@OnItemLongClickListener@OnItemSelected@OnPageChange

    • 参数数量不固定,可为参数的子类
    • 多回掉方法的监听,使用 value 和 callback
    // View.OnClickListener
    @OnClick(R.id.submit)
    public void submit(View view) {
    }
    
    @OnClick(R.id.submit)
    public void submit() {  // 无参
    }
    
    @OnClick(R.id.submit)
    public void sayHi(Button button) {  // 任意参数,默认强转,可为绑定View的子类
      button.setText("Hello!");
    }
    
    @OnClick({ R.id.door1, R.id.door2, R.id.door3 })  // 多 IDs 绑定
    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,绑定自己的监听,不指定 ID
    public class FancyButton extends Button {
        @OnClick
        public void onClick() {
        }
    }
    
    // TextWatcher
    @OnTextChanged(R.id.example)
    void onTextChanged(CharSequence s, int start, int before, int count) {
    }
    
    @OnTextChanged(value = R.id.example, callback = BEFORE_TEXT_CHANGED)
    void onBeforeTextChanged(CharSequence s, int start, int count, int after) {
    }
    
    @OnTextChanged(value = R.id.example, callback = AFTER_TEXT_CHANGED)
    void onAfterTextChanged(Editable s) {
    }
    
    // View.OnLongClickListener
    @OnLongClick(R.id.example)
    boolean onLongClick(View v) {
        return true;
    }
    
    // View.OnTouchListener
    @OnTouch(R.id.example)
    boolean onTouch(View v, MotionEvent event) {
        return false;
    }
    
    // CompoundButton.OnCheckedChangeListener
    @OnCheckedChanged(R.id.example)
    void onChecked(CompoundButton buttonView, boolean isChecked) {
    }
    
    // TextView.OnEditorActionListener
    @OnEditorAction(R.id.example)
    boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
        return true;
    }
    
    // View.OnFocusChangeListener
    @OnFocusChange(R.id.example)
    void onFocusChanged(View v, boolean hasFocus) {
    }
    
    // AdapterView.OnItemClickListener
    @OnItemClick(R.id.example_list)
    void onItemClick(AdapterView<?> parent, View view, int position, long id) {
    }
    
    // AdapterView.OnItemLongClickListener
    @OnItemLongClick(R.id.example_list)
    boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
        return true;
    }
    
    // AdapterView.OnItemSelectedListener
    @OnItemSelected(R.id.example_list)
    void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
    }
    
    @OnItemSelected(value = R.id.example_list, callback = NOTHING_SELECTED)
    void onNothingSelected() {
    }
    
    // ViewPager.OnPageChangeListener
    @OnPageChange(R.id.example_pager)
    void onPageSelected(int position) {
    }
    
    @OnPageChange(value = R.id.example_pager, callback = PAGE_SCROLL_STATE_CHANGED)
    void onPageStateChanged(int state) {
    }
    
    @OnPageChange(value = R.id.example_pager, callback = PAGE_SCROLLED)
    void onPageStateChanged(int position, float positionOffset, int positionOffsetPixels) {
    }
    

    选择绑定

    默认情况下,如果不能找到目标视图,则将抛出异常。@Nullable@Optional,存在即绑定,不存在即忽略,不抛异常

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

    绑定重置

    public class FancyFragment extends Fragment {
        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);
            // ...
            return view;
        }
    
        @Override public void onDestroyView() {
            super.onDestroyView();
            unbinder.unbind();
        }
    }
    

    额外

    ButterKnife.findById()自动强转,第一个参数可为 View, Activity, Dialog

    ImageView photo = ButterKnife.findById(view, R.id.photo);
    

    进阶用法

    ButterKnife.apply()

    // 绑定View
    @BindViews({ R.id.first_name, R.id.middle_name, R.id.last_name })
    List<EditText> nameViews;
    
    // 实现 Action 和 Setter 接口,定义动作
    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);
        }
    };
    
    // 调用
    ButterKnife.apply(nameViews, DISABLE);
    ButterKnife.apply(nameViews, ENABLED, false);
    ButterKnife.apply(nameViews, View.ALPHA, 0.0f);
    

    相关文章

      网友评论

        本文标题:ButterKnife8 使用说明

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