ButterKnife的简单实用

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接: https://blog.csdn.net/qq_33334951/article/details/102591250

ButterKnife的简单实用

1.简介

  • 专注于 Android 系统的View 注入框架。
  • 减少大量的findViewById 以及 setOnClickListener代码。
  • 官网:GitHub

2.使用方法

2.1 环境

  • API 28
  • JAVA 8
  • Android Studio 3.4.2
  • 添加依赖库
implementation 'com.jakewharton:butterknife:10.2.0'
annotationProcessor 'com.jakewharton:butterknife-compiler:10.2.0'

2.2 绑定控件

  • 使用注解 @BindView 绑定控件id。
  • Activity使用时要先绑定活动。(注释:1)
  • 控件类的修饰符不能是 privatestatic
public class MainActivity extends AppCompatActivity {
    @BindView(R.id.bt_ex1)
    Button buttonEx1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);//1
    }
}

  • @BindViews 绑定多个控件
@BindViews({R.id.bt_ex1,R.id.bt_ex2,R.id.bt_ex3})
List<Button> buttonList;

2.3 绑定资源

  • @BindString
  • @BindArray
  • @BindBool
  • @BindColor
  • @BindDimen
  • @BindDrawable
  • @BindBitmap
//部分举例
@BindString(R.string.titile)
    String title;

@BindArray(R.array.names)
    String[] nameArr;

2.4 绑定监听

  • @OnClick
  • @OnTextChanged
  • @OnTouch
  • @OnItemClick
@OnClick(R.id.bt_ex1)
public void showToast(){
	Toast.makeText(this,"click!",Toast.LENGTH_SHORT).show();
}

2.5 可选绑定

  • @Nullable:防止找不到资源产生异常
@Nullable
@BindView(R.id.bt_ex1)
Button buttonEx1;

3.在Fragment和Adapter中使用ButterKnife

  • Fragment:
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
	View view =inflater.inflate(R.layout.activity_main,container,false);
	ButterKnife.bind(this,view);
	return view;
}
  • Adapter:
class ViewHolder{
    @BindView(R.id.bt_ex1)
    Button buttonEx1;
    public ViewHolder(View view){
        ButterKnife.bind(this,view);
    }
}

猜你喜欢

转载自blog.csdn.net/qq_33334951/article/details/102591250