0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

[Android]ビューバインディングを使ってfindViewByIdを置き換える

Posted at

Androidの実装において、findViewByIdを使ってActivityやFragmentでViewを取得することはこれまでの通例ですが、正直面倒くさいです
実際に書いてみると下記のようになります

Javaコード
TextView textView = (TextView)findViewById(R.textView)
textView.setText("Test Text")
Kotlinコード
var textView: TextView = findViewById(R.id. R.textView)
textView = "Test Text"

上記の通りViewが増えるたびにfindViewByIdが増えてしまいます。
今回ご紹介するビューバインディングではこの煩わしいコードを無くしてもっと便利にできます

ビューバインディングとは

ビューを操作するコードを簡単に記述できる機能です。
ビューバインディンを有効にすると、各レイアウトファイルごとにバインディングクラスが自動で生成されます。
このクラスには実際のレイアウトファイルに記載されたIDを持つ各Viewへの参照を持っています
このバインディングクラスのViewへの参照をAcitvityやFragmentから呼び出すことでfindViewByIdを使ったViewの取得をしなくて済むようになります。

ビューバインディングの導入

追加するアプリ・モジュールのbuild.gradleに下記を記載します
導入はこれだけです
※日本語のAndroidDeveloperページではbuildFeaturesではなく、viewBindingとなっているので注意。viewBindingでの記載はもう古いようです

build.gradle(app)
android {
    ...
    buildFeatures {
        viewBinding = true
    }
}
    

これだけで上記のTextViewの呼び出しが下記のように簡単になります

Javaコード
binding.textView.setText("Test Text")
Kotlinコード
binding.textView = "Test Text"

※上記のようなコードにするにはAcitivityやFragmentで少しだけ準備が必要です
実際の使用方法は下記Developerを参照するとわかりやすいです
https://developer.android.com/topic/libraries/view-binding?hl=ja#usage

※注意点
Developerでは「result_profile.xml 」というレイアウト ファイルがあることを前提としています
下記のようにBindingクラスはレイアウトの名前を元に生成されます。
使用する際はご自身の作成したレイアウト名に置き換えるようにしてください

AndroidDeveloperの例
result_profile.xml → ResultProfileBinding

例.)
main_fragment.xml → MainFragmentBinding

参照

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?