ButterKnife简单使用

在项目的build.gradle中添加一行代码

dependencies {
        classpath 'com.android.tools.build:gradle:3.2.0'

        //Butterknife
        classpath 'com.jakewharton:butterknife-gradle-plugin:8.8.1'
    }

在你的app里导入依赖

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

布局文件

<?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">

    <Button
        android:id="@+id/btn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="点击"
        />
    <TextView
        android:id="@+id/tv"
        app:layout_constraintTop_toBottomOf="@+id/btn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
</android.support.constraint.ConstraintLayout>

Main中的代码

public class MainActivity extends AppCompatActivity {
    //绑定控件
    @BindView(R.id.btn)
    Button button;
    @BindView(R.id.tv)
    TextView textView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //一定记住在 onCreate() 中调用 ButterKnife.bind(this);, 否则不起作用
        ButterKnife.bind(this);
    }

    //绑定事件
    @OnClick(R.id.tv)
    void tvOnClick(View view){
        String s = ((TextView) view).getText().toString();
        Toast.makeText(this, s, Toast.LENGTH_SHORT).show();
    }

    @OnClick(R.id.btn)
    void btnOnClick(){
        Toast.makeText(this, "123456", Toast.LENGTH_SHORT).show();
        textView.setText("123456");
    }
}

猜你喜欢

转载自blog.csdn.net/xieyu1999/article/details/85260967