Android
 Computer >> コンピューター >  >> プログラミング >> Android

【Android】ButterKnifeの使い方をサンプルコード付きで徹底解説!


この記事では、Androidアプリ開発で定番だったアノテーションライブラリ「ButterKnife」の使い方を、実際にサンプルプロジェクトを動かしながらステップごとに解説します。

ButterKnifeとは?

ButterKnifeは、Jake Wharton氏が開発したAndroid向けのビューインジェクションライブラリです。従来のようにfindViewById()でビューを1つずつ取得する代わりに、@BindViewアノテーションをフィールドに付けるだけで、対応するビューが自動的に注入されます。ボイラープレートコードが減り、Activityのコードがすっきりと読みやすくなるのが大きなメリットです。

手順1:新規プロジェクトを作成する

まず、Android Studioで新しいプロジェクトを作成します。メニューから「File → New Project」を選択し、プロジェクト名などの必要事項を入力してプロジェクトを生成してください。本記事ではプログラミング言語にJavaを使用します。

手順2:レイアウトファイルを編集する

res/layout/activity_main.xml を開き、以下のコードを記述します。TextViewを3つとButtonを1つ縦に並べたシンプルなレイアウトです。

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center_horizontal"
    android:orientation="vertical">

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="..........."
        android:textSize="16sp"
        android:textStyle="bold"
        android:textAllCaps="true" />

    <TextView
        android:id="@+id/textView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="..........."
        android:textSize="16sp"
        android:textStyle="bold"
        android:textAllCaps="true" />

    <TextView
        android:id="@+id/textView3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="..........."
        android:textSize="16sp"
        android:textStyle="bold"
        android:textAllCaps="true" />

    <Button
        android:id="@+id/btnLoadText"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textSize="16sp"
        android:textStyle="bold"
        android:text="Load Text" />

</LinearLayout>

手順3:build.gradleに依存関係を追加する

次に、build.gradle(Module: app)を開き、dependenciesブロックに以下の2行を追加します。

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

追加後は画面右上に表示される「Sync Now」をクリックし、Gradleとの同期を実行してください。これでButterKnifeがプロジェクト内で使用可能になります。

手順4:MainActivity.javaを実装する

src/MainActivity.java に以下のコードを記述します。

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import butterknife.BindView;
import butterknife.ButterKnife;

public class MainActivity extends AppCompatActivity {

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

    @BindView(R.id.textView2)
    TextView textView2;

    @BindView(R.id.textView3)
    TextView textView3;

    @BindView(R.id.btnLoadText)
    Button button;

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

        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                textView.setText("Hi, How are you?");
                textView2.setText("Have a nice day!");
                textView3.setText("You are so good.");
            }
        });
    }
}

@BindViewを付けた各フィールドには、onCreate()内でButterKnife.bind(this)を呼び出した時点で、指定したIDに対応するビューが自動的に代入されます。そのため、findViewById()を1つずつ記述する必要はありません。

補足:@OnClickでクリック処理をもっと簡潔に

ボタンのクリックイベントもButterKnifeならさらにシンプルに書けます。setOnClickListenerの代わりに、以下のように@OnClickアノテーションを使う方法もあります。

@OnClick(R.id.btnLoadText)
public void onBtnLoadTextClick() {
    textView.setText("Hi, How are you?");
    textView2.setText("Have a nice day!");
    textView3.setText("You are so good.");
}

手順5:AndroidManifest.xmlを確認する

androidManifest.xml は以下の内容になります。ButterKnifeの利用に特別なパーミッションは不要です。MainActivityがランチャーアクティビティとして正しく登録されていることを確認しておきましょう。

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android"
    package="app.com.sample">

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

アプリを実行してみよう

準備ができたらアプリを実行します。実機のAndroidスマートフォンをパソコンに接続し、Android Studioでいずれかのアクティビティファイルを開いて、ツールバーの「Run」アイコンをクリックしてください。デバイス選択ダイアログで接続した端末を選ぶと、端末に以下のような初期画面が表示されます。

【Android】ButterKnifeの使い方をサンプルコード付きで徹底解説!

【Android】ButterKnifeの使い方をサンプルコード付きで徹底解説!

起動直後は3つのTextViewにプレースホルダーのドットが表示されています。ここで「Load Text」ボタンをタップすると、「Hi, How are you?」「Have a nice day!」「You are so good.」の3つのメッセージがそれぞれのTextViewに切り替わります。

まとめ:今後はViewBindingも検討しよう

ButterKnifeを使えば、findViewById()の繰り返しを排除し、ビューの取得処理をアノテーションに任せられることが分かりました。ただし、ButterKnifeは現在メンテナンスモードに入っており、新規開発においてはGoogleが推奨するJetpackのViewBindingやDataBindingの採用が推奨されています。既存プロジェクトの保守では引き続き有効なので、プロジェクトの状況に応じて適切に使い分けるとよいでしょう。


  1. Androidで文字列を比較する方法を解説!equals・==・compareToの使い分け

    Androidで文字列を比較する方法 この記事では、Androidアプリ開発における文字列比較の手法として、equals()メソッド、==演算子、compareTo()メソッドの3つの方法を、実際のサンプルコードを交えて解説します。 ステップ1:新規プロジェクトの作成 Android Studioを開き、「File」→「New Project」を選択して、必要な項目を入力し、新しいプロジェクトを作成します。 ステップ2:レイアウトファイル(activity_main.xml)の編集 res/layout/activity_main.xml に以下のコードを追加します。 <?xml v

  2. 【Android開発】StringBufferの使い方を徹底解説!文字列操作の基本メソッドまとめ

    はじめに:StringBufferとは?具体的なサンプルコードに入る前に、まず「StringBuffer(ストリングバッファ)」について簡単に確認しておきましょう。StringBufferクラスは、変更可能(ミュータブル)な文字列を扱うためのクラスです。JavaではStringオブジェクトは不変(イミュータブル)であるため、文字列を頻繁に連結・編集する場合には、新しいオブジェクトが都度生成されてパフォーマンスが低下します。一方、StringBufferは既存の文字列を直接書き換えられるため効率的で、さらにスレッドセーフである点も大きな特徴です。マルチスレッド環境でも安全に文字列操作が行えます。