ButterKnife 的配置和使用

下面以8.8.1版本为例,简单介绍下ButterKnife的配置和使用

项目配置

1.在module的build.gradle 文件中的dependencies标签中添加代码如下

implementation 'com.jakewharton:butterknife:8.8.1'
annotationProcessor 'com.jakewharton:butterknife-compiler:8.8.1'

2.安装ButterKnife插件:


代码中简单使用

XML

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="45dp"
        android:layout_marginTop="55dp"
        android:text="Button"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</android.support.constraint.ConstraintLayout>

Android src

1.在 setContentView(R.layout.activity_main)下面添加ButterKnife.bind(this)代码

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

2.选中 activity_main,右击 从上下文菜单中选着General Bufferknife Injections (快捷 command + shift + B)会自动生成注解

    @BindView(R.id.textView)
    TextView textView;
    @BindView(R.id.button)
    Button button;

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

3.绑定button的监听事件

    @OnClick({R.id.button})
    public void onButtonClicked(View view){
        Toast.makeText(this,"onButtonClicked",Toast.LENGTH_SHORT).show();
    }

以上内容就是ButterKnife的简单配置和使用(项目地址)。

进一步了解,请参考一下链接:

英文使用说明ButterKnife API文档 ButterKnife源码 。







猜你喜欢

转载自blog.csdn.net/xingfuyusheng/article/details/80793249