iT邦幫忙

2021 iThome 鐵人賽

DAY 20
1
Mobile Development

刮掉Web Development的我,與撿到的Android Development系列 第 20

[Lesson20] ButterKnife

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
https://ithelp.ithome.com.tw/upload/images/20210924/20129566gPBDdsg3g4.png

選擇Plugins,上面輸入Android ButterKnife Injections後按下Install,完成後按下OK就好了
https://ithelp.ithome.com.tw/upload/images/20210924/20129566I2aJDaTp7u.png

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
https://ithelp.ithome.com.tw/upload/images/20210924/20129566M6aToszvAM.png

ButterKnife injections
https://ithelp.ithome.com.tw/upload/images/20210924/20129566HteMwHd2LA.png

confirm
https://ithelp.ithome.com.tw/upload/images/20210924/20129566j4bxzAjBER.png

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);
    }
}

謝謝大家願意花時間閱讀,小弟弟我在此鞠躬/images/emoticon/emoticon41.gif


上一篇
[Lesson19] View Binding
下一篇
[Lesson21] Kotlin - 宣告變數
系列文
刮掉Web Development的我,與撿到的Android Development30

1 則留言

0
胭脂虎
iT邦新手 2 級 ‧ 2021-10-05 00:56:54

謝謝您詳細的擷圖及教學!

我要留言

立即登入留言