ButterKnife可以讓我們在宣告元件時之後不用再打findViewById這行,可以幫忙省下宣告元件的時間。
build.gradle:
dependencies {
implementation 'com.jakewharton:butterknife:10.2.3'
annotationProcessor 'com.jakewharton:butterknife-compiler:10.2.3'
}
android {
...
// Butterknife requires Java 8.
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
}
ButterKnife Injections:
Android Studio中選擇 File -> Settings
選擇Plugins,上面輸入Android ButterKnife Injections後按下Install,完成後按下OK就好了
activity_main:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TextView
android:id="@+id/text"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:text="HELLO"/>
<Button
android:id="@+id/button"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="按鈕"
android:layout_below="@+id/text"/>
</RelativeLayout>
MainActivity:
右鍵 -> Generate
ButterKnife injections
confirm
public class MainActivity extends AppCompatActivity {
@BindView(R.id.text)
TextView text;
@BindView(R.id.button)
Button button;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.bind(this);
}
}
謝謝大家願意花時間閱讀,小弟弟我在此鞠躬