打开build.gradle配制,输入如图下所示:
compile 'com.jakewharton:butterknife:8.4.0' annotationProcessor 'com.jakewharton:butterknife-compiler:8.4.0'
在activity里选择需要加载的xml文件,右健打开,如图下所示:
这里给控件取名
完成
代码如下所示:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#ffffff"
android:orientation="vertical">
<TextView
android:id="@+id/tv_name"
android:layout_width="match_parent"
android:layout_height="50dp"
android:textSize="30dp"
android:gravity="center"
android:textColor="@color/colorPrimaryDark"
android:text="Hello World!" />
<Button
android:id="@+id/btn_ok"
android:layout_width="match_parent"
android:layout_height="100dp"
android:textSize="46sp"
android:gravity="center"
android:textColor="@color/colorAccent"
android:text="中奖了"/>
<Button
android:id="@+id/btn_cancel"
android:layout_width="match_parent"
android:layout_height="100dp"
android:textSize="46sp"
android:gravity="center"
android:textColor="@color/colorAccent"
android:text="取消"/>
</LinearLayout>
package com.nnddkj.mytestdemo;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
public class MainActivity extends AppCompatActivity {
@BindView(R.id.tv_name)
TextView tvName;
@BindView(R.id.btn_ok)
Button btnOk;
@BindView(R.id.btn_cancel)
Button btnCancel;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.bind(this);
tvName.setText("张三");
}
@OnClick(R.id.btn_ok)
public void onOkclick() {
Toast.makeText(MainActivity.this,"中奖了",Toast.LENGTH_SHORT).show();
}
}
apply plugin: 'com.android.application'
android {
compileSdkVersion 25
buildToolsVersion "25.0.0"
defaultConfig {
applicationId "com.nnddkj.mytestdemo"
minSdkVersion 19
targetSdkVersion 25
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
exclude group: 'com.android.support', module: 'support-annotations'
})
compile 'com.android.support:appcompat-v7:25.0.1'
testCompile 'junit:junit:4.12'
compile 'com.jakewharton:butterknife:8.4.0'
annotationProcessor 'com.jakewharton:butterknife-compiler:8.4.0'
}