ButterKnifer使用

1.集成

github地址: https://github.com/JakeWharton/butterknife

1.1在主Moduel中的使用

在主moduel中的build.gradle中添加一下配置

android {
...
// Butterknife requires Java 8.
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
} dependencies {
implementation 'com.jakewharton:butterknife:10.2.0'
annotationProcessor 'com.jakewharton:butterknife-compiler:10.2.0'
}

如果您使用的是Kotlin,请替换annotationProcessorkapt

1.2在Library projects项目中使用

1.在Android project的build.gradle中添加

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

2.在Library的buid.gradle中添加如下配置

apply plugin: 'com.android.library'
apply plugin: 'com.jakewharton.butterknife'

3.确保在Butter knife annotations中使用R2替换R。

class ExampleActivity extends Activity {
@BindView(R2.id.user) EditText username;
@BindView(R2.id.pass) EditText password;
...
}

2. ButterKnife的基本使用场景

2.1 在Activity中绑定ButterKnife:

    @BindView(R.id.bt)
Button bt;
@BindView(R.id.bt2)
Button bt2; @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.bind(this);
} @OnClick({R.id.bt, R.id.bt2})
public void onViewClicked(View view) {
switch (view.getId()) {
case R.id.bt:
Toast.makeText(this,"button1被点击了",Toast.LENGTH_LONG).show();
break;
case R.id.bt2:
Toast.makeText(this,"button2被点击了",Toast.LENGTH_LONG).show();
break;
}
}

2.2 在Fragment中绑定ButterKnife

    private Unbinder unbinder;
@BindView(R.id.bt1)
Button bt1;
@BindView(R.id.bt2)
Button bt2; @Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container,
@Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_first, container, false);
unbinder= ButterKnife.bind(this,view);
return view;
} @OnClick({R.id.bt1, R.id.bt2})
public void onViewClicked(View view) {
switch (view.getId()) {
case R.id.bt1:
break;
case R.id.bt2:
break;
}
} @Override
public void onDestroyView() {
super.onDestroyView();
unbinder.unbind();//视图销毁时必须解绑
}

2.3 在Adapter的ViewHolder中绑定ButterKnife

public class ItemAdapter extends RecyclerView.Adapter<ItemAdapter.ViewHolder> {

    private Context context;
private List<Item> datas; public ItemAdapter(Context context, List<Item> datas) {
this.context = context;
this.datas = datas;
} @NonNull
@Override
public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_rv, parent,
false);
return new ViewHolder(view);
} @Override
public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
holder.img.setImageResource(datas.get(position).getImgId());
holder.tv.setText(datas.get(position).getContent());
holder.img.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) { Toast.makeText(context,"图片被点击了...",Toast.LENGTH_SHORT).show();
}
});
} @Override
public int getItemCount() {
return datas.size();
} class ViewHolder extends RecyclerView.ViewHolder {
@BindView(R.id.img)
ImageView img;
@BindView(R.id.tv)
TextView tv; public ViewHolder(@NonNull View itemView) {
super(itemView);
ButterKnife.bind(this, itemView);
}
}
}

3. Butterknife具体使用

3.1 绑定View

1.单个控件id注解: @BindView()

@BindView(R.id.bt)Button bt;

2.布局内多个控件id注解; @BindViews()

@BindViews({R.id.butter,R.id.butter1,R.id.butter2})
List<Button> buttons;

3.2 绑定资源文件

1.绑定string 字符串:@BindString()

@BindString(R.string.app_name) //绑定资源文件中string字符串
String name;

2.绑定array数组:@BindArray()

<resources>
<string name="app_name">开眼视频</string> <string-array name="weather">
<item>高温</item>
<item>低温</item>
<item>阴天</item>
<item>雨天</item>
<item>晴天</item>
</string-array> </resources>
@BindArray(R.array.weather) //绑定string资源里面array数组
String [] weathers ;

3.绑定颜色值:@BindColor( )

@BindColor( R.color.colorPrimary) //绑定color文件中颜色值
int colorPrimary;

4.绑定Bitmap:@BindBitmap( )

@BindBitmap(R.mipmap.ic_launcher)
Bitmap bitmap;

5.其他资源绑定:

@BindBool(R.bool.is_tablet) boolean isTablet; //绑定真假boolean

@BindFont(R.font.comic_sans) Typeface comicSans; //绑定字体文字

@BindDimen(R.dimen.horizontal_gap) int gapPx //绑定尺寸
@BindDimen(R.dimen.horizontal_gap) float gap; //绑定尺寸 @BindAnim(R.anim.fade_in) Animation fadeIn; //绑定动画 @BindDrawable(R.drawable.placeholder) Drawable placeholder;//绑定Drawable

3.3 绑定监听事件

1.绑定控件点击事件:@OnClick( )

  • 单个控件点击事件:
 @OnClick(R.id.butter)
public void onClick(){
Toast.makeText(this, "绑定单个view事件", Toast.LENGTH_SHORT).show();
}
  • 多个控件同一点击事件:
@OnClick({R.id.share_wechat,R.id.share_moments,R.id.share_weibo})
public void onClick(){
Toast.makeText(this, "都执行此事件", Toast.LENGTH_SHORT).show();
}
  • 多个控件点击事件:
  @OnClick({R.id.share_wechat,R.id.share_moments,R.id.share_weibo})
public void onClick(View v) {
switch (v.getId()){
case R.id.share_wechat:
sharePlatform(Wechat.NAME);
break;
case R.id.share_moments:
sharePlatform(WechatMoments.NAME);
break;
case R.id.share_weibo:
sharePlatform(SinaWeibo.NAME);
break;
}
}

2.绑定控件长按事件:@OnLongClick( )

@OnLongClick( R.id.button1 ) //给 button1 设置一个长按事件
public boolean onLongClick (){
Toast.makeText(this, "is a long click", Toast.LENGTH_SHORT).show();
return true ;
}

3.其他事件绑定

//选中,选中取消
@OnCheckedChanged(R.id.example)
public void onChecked(boolean checked) {
Toast.makeText(this, checked ? "Checked!" : "Unchecked!", Toast.LENGTH_SHORT).show();
} //软键盘的功能按键
@OnEditorAction(R.id.example)
public boolean onEditorAction(KeyEvent key) {
Toast.makeText(this, "Pressed: " + key, Toast.LENGTH_SHORT).show();
return true;
} //焦点改变
@OnFocusChange(R.id.example)
public void onFocusChanged(boolean focused) {
Toast.makeText(this, focused ? "Gained focus" : "Lost focus", Toast.LENGTH_SHORT).show();
} //Item长按,返回true则可以拦截onItemClick
@OnItemLongClick(R.id.example_list)
public boolean onItemLongClick(int position) {
Toast.makeText(this, "Long clicked position " + position + "!", Toast.LENGTH_SHORT).show();
return true;
} //Item点击事件
@OnItemClick(R.id.example_list)
public void onItemClick(int position) {
Toast.makeText(this, "Clicked position " + position + "!", Toast.LENGTH_SHORT).show();
} //Item被选择事件
@OnItemSelected(R.id.example_list)
public void onItemSelected(int position) {
Toast.makeText(this, "Selected position " + position + "!", Toast.LENGTH_SHORT).show();
} //EditText里面的文本变化事件
@OnTextChanged(R.id.example)
public void onTextChanged(CharSequence text) {
Toast.makeText(this, "Text changed: " + text, Toast.LENGTH_SHORT).show();
} //页面改变事件
@OnPageChange(R.id.example_pager)
public void onPageSelected(int position) {
Toast.makeText(this, "Selected " + position + "!", Toast.LENGTH_SHORT).show();
} //触摸事件
@OnTouch(R.id.example)
public boolean onTouch() {
Toast.makeText(this, "Touched!", Toast.LENGTH_SHORT).show();
return false;
}

3.4 Action接口与Setter接口

Action接口主要是为了对View或者Views进行管理初始化等操作,而Setter接口其实就是对view或者views的属性或者值进行操作.使用 ButterKnife.apply()方法启用接口.

ButterKnife.Action<View> action = new ButterKnife.Action<View>() {
@Override
public void apply(@NonNull View view, int index) {
if (view instanceof Button ){
Button button = (Button) view;
button.setText("点击我");
}
}
}; ButterKnife.Setter<View,Boolean> setter = new ButterKnife.Setter<View, Boolean>() {
@Override
public void set(@NonNull View view, Boolean value, int index) {
view.setEnabled(value);
}
}; @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.bind(this);
ButterKnife.apply(buttons,action);//初始化或修改每个view的属性值
ButterKnife.apply(buttons,setter,true);
}

4 ButterKnife Zelezny插件

打开Android studio:点击File--->Settings--->Plugins--->搜索 Butterknife Zelezny--->下载安装--->重启Android studio.

参考;

Android常用之Butterknife使用详解

ButterKnifer使用的更多相关文章

随机推荐

  1. IntelliJ IDEA和Eclipse快捷键对比总结

  2. 1.opencv_画图

    #导入工具包 import numpy as np import cv2 import matplotlib.pyplot as plt # 定义显示图片 def show(image): plt.i ...

  3. programble blending --frame buffer fetch

    https://developer.arm.com/-/media/Files/pdf/graphics-and-multimedia/Efficient%20Rendering%20with%20T ...

  4. MySQL_DBA整理

     MySQL_DBA整理(转) 2011-01-26 16:51:41 分类: Mysql/postgreSQL 转自:丁丁:http://www.itpub.net/thread-831154-2- ...

  5. web 9个令人震惊的WebGL示例

    20个使用WebGL和Three.js实现的网页场景 https://www.open-open.com/news/view/9d8136 20个使用WebGL和Three.js实现的网页场景 htt ...

  6. js中for..of..和迭代器

    for..of是ES6中引入的新特性,它主要的作用是:循环一个可迭代的对象. 它可以循环遍历,数组.字符串.Set对象等等 示例一: let str = 'hello' for (item of st ...

  7. SQL 修复表

    alter database dcdata set single_user with rollback immediate设置为单用户模式然后执行修复.DBCC CHECKTABLE(ZLBZSGPH ...

  8. C# socket异步通讯

    Server: using System; using System.Net; using System.Net.Sockets; using System.Text; namespace TCP_S ...

  9. USACO14MAR The Lazy Cow(Gold)

    题目 题意:平面上有 \(n\) 块草地,第 \(i\) 块草地坐标为 \((x_i,y_i)\) ,上面有 \(g_i\) 个单位的草.Bessie 可以吃到距离起始点不超过 \(k\)(这里是曼哈 ...

  10. Python身份运算符

    运算符 描述 实例 is is 是判断两个标识符是不是引用自一个对象 x is y, 类似 id(x) == id(y) , 如果引用的是同一个对象则返回 True,否则返回 False is not ...