ButterKnife使用详解

前言

ButterKnife是控件注入框架,可以帮助安卓开发者省去初始化控件的重复性工作,简单快捷地初始化布局文件中的控件,极大地提升开发效率。 
项目地址-传送门

导入ButterKnife至项目中

1.在工程的build.gradle中导入butterknife插件 
这里写图片描述


buildscript {
    repositories {
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:2.3.0'
        //加入下面这段代码
        classpath 'com.jakewharton:butterknife-gradle-plugin:8.5.1'
    }
}

allprojects {
    repositories {
        jcenter()
    }
}



 
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20

2.在项目的build.gradle中添加butterknife的插件,即是app中的builde.gradle 
这里写图片描述

apply plugin: 'com.android.application'
//加入下面这段代码
apply plugin: 'com.jakewharton.butterknife'
 
 
  • 1
  • 2
  • 3

3.在项目的build.gradle中添加依赖,然后同步项目,即可下载butterknife库至项目中


dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])

    compile 'com.android.support:appcompat-v7:25.2.0'

    //加入下面这两行代码
    compile 'com.jakewharton:butterknife:8.5.1'
    annotationProcessor 'com.jakewharton:butterknife-compiler:8.5.1'

}
 
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11

简单使用butterknife初始化控件

1.创建一个android工程,布局如下 
这里写图片描述

2.在activity中的oncreate()方法里初始化butterknife框架 
注意初始化要放在setView()之后

 @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_butter_knife_test);
        ButterKnife.bind(this);
    }
 
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

3.查找TextView与Button

public class ButterKnifeTestActivity extends AppCompatActivity {
    //绑定控件,省去了写findviewbyid的重复性操作
    @BindView(R.id.tv_test1)
    private TextView tvTest;
    @BindView(R.id.btn_test1)
    private Button btnTest;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_butter_knife_test);
        ButterKnife.bind(this);
    }
}
 
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14

4.测试控件是否被正确初始化

  tvTest.setText("文本控件已被初始化");
  btnTest.setText("按钮被初始化");
 
 
  • 1
  • 2

运行工程,结果如下,报了一个编译错误。 
这里写图片描述

Error:(14, 22) 错误: @BindView fields must not be private or static. (com.example.hapzhu.andrioddemotest.ButterKnifeTestActivity.tvTest)
 
 
  • 1

意思是控件不能被声明为私有的或者是静态的,看来butterknife框架是对控件声明有限制的,将private去掉即可。

    @BindView(R.id.tv_test1)
   TextView tvTest;
    @BindView(R.id.btn_test1)
    Button btnTest;
 
 
  • 1
  • 2
  • 3
  • 4

这里写图片描述

5.给按钮设置点击监听事件

@OnClick(R.id.btn_test1)
    public void onclick(View view){
        btnTest.setText("我被点击了");
        tvTest.setText("天若有情天亦老");
    }
 
 
  • 1
  • 2
  • 3
  • 4
  • 5

随便写一个方法,参数可以放View也可以不放任何参数, 
在方法上一行注解OnClick即可绑定点击事件,注意该方法必须不能为private或者是static的,与声明时规则一致。 
这里写图片描述

下载注解插件进行一键初始化

打开android的plugins中心,搜索butterknife 
这里写图片描述 
点击browse repo,下载前两个插件都可以。 
这里写图片描述 
下载完成后,回到activity代码的setContentview处,右键布局文件名,注意一定要把光标停在布局文件名上 
这里写图片描述 
选择Generate,这时可以看到生成butterknife注解的选项,如果光标不放在布局文件名上,则看不到该选项。 
这里写图片描述 
点击生成butterknife注解 
这里写图片描述 
插件将布局文件中的所有id都加载出来了,还可以设置点击事件,点击confirm即可快速初始化控件,非常方便。

   @BindView(R.id.tv_test1)
    TextView tvTest1;
    @BindView(R.id.btn_test1)
    Button btnTest1;
    @BindView(R.id.et_test1)
    EditText etTest1;
    @BindView(R.id.lv_test1)
    ListView lvTest1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_butter_knife_test);
        ButterKnife.bind(this);
        tvTest1.setText("文本控件已被初始化");
        btnTest1.setText("按钮被初始化");

    }


    @OnClick(R.id.btn_test1)
    public void onViewClicked() {
        btnTest1.setText("我被点击了");
        tvTest1.setText("天若有情天亦老");
    }
 
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25

效果与手动注解一样,对于安卓开发工作者来说,这个插件确实是个神器,节省了大量初始化控件的时间。

其它用途绑定

绑定res里资源对象
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
  // ...
}
 
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
绑定Fragment
public class FancyFragment extends Fragment {
  @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;
  }
}
 
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
绑定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);
      //利用构造器将item的view传入viewHolder中
      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) {
    //在构造器中绑定view
      ButterKnife.bind(this, view);
    }
  }
}
 
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
绑定控件ID直接将控件添加至集合或数组中
@BindViews({ R.id.first_name, R.id.middle_name, R.id.last_name })
//nameViews的集中中添加了三个edittext对象
List<EditText> nameViews;
 
 
  • 1
  • 2
  • 3
一次性改变集合中所有对象的值-apply
//DISABLE是一个接口的实现类
ButterKnife.apply(nameViews, DISABLE);
ButterKnife.apply(nameViews, ENABLED, false);
Action and Setter interfaces allow specifying simple behavior.

//初始化DISABLE
static final ButterKnife.Action<View> DISABLE = new ButterKnife.Action<View>() {
  @Override public void apply(View view, int index) {
  //将view设为不可输入
    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);
  }
};

//如果是view的自带属性,可以不用实现接口,直接使用

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

 
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
绑定listview的item点击事件
@OnItemSelected(R.id.list_view)
void onItemSelected(int position) {
  // TODO ...
}
 
 
  • 1
  • 2
  • 3
  • 4
findviewById的简化

适用于从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);

demo项目地址

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
使用ButterKnife,需要进行以下步骤: 1. 在项目的build.gradle文件中添加ButterKnife的依赖: ```groovy dependencies { implementation 'com.jakewharton:butterknife:10.2.3' annotationProcessor 'com.jakewharton:butterknife-compiler:10.2.3' } ``` 2. 在需要使用ButterKnife的Activity或Fragment中,使用`@BindView`注解来绑定视图元素。 ```java public class MainActivity extends AppCompatActivity { @BindView(R.id.textView) TextView textView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); ButterKnife.bind(this); // 现在可以直接使用textView了 textView.setText("Hello ButterKnife!"); } } ``` 3. 调用`ButterKnife.bind(this)`方法来完成视图的绑定。这通常是在Activity的`onCreate()`方法中进行。 4. 在需要为视图设置点击事件、长按事件等的地方,使用`@OnClick`、`@OnLongClick`等注解来定义相应的事件处理方法。 ```java public class MainActivity extends AppCompatActivity { @BindView(R.id.button) Button button; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); ButterKnife.bind(this); // 设置点击事件处理方法 button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // 处理点击事件 } }); } @OnClick(R.id.button) void onButtonClick() { // 处理点击事件,使用注解方式 } @OnLongClick(R.id.button) boolean onButtonLongClick() { // 处理长按事件,使用注解方式 return true; } } ``` 这样,你就可以使用ButterKnife来简化视图绑定和事件处理的工作了。记得在合适的时机调用`ButterKnife.unbind(this)`方法来解绑视图。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值