1
0

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]ViewBindingを使いたい!

Last updated at Posted at 2021-02-20

###ViewBindingを使いたい理由
xmlファイルでViewに指定したidを用いてアクティビティやフラグメントを書く際、findViewByIdを逐一書かなくて良きなのと、型安全なので記述ミスがなくなる。数か月くらい前に、話題になりましたが、まだ使えてない!時代のビックウェーブに乗り遅れた!という人向けに書いてみました。実装は、簡単です!
https://developer.android.com/topic/libraries/view-binding

// モジュールの方ね!書けたらSync now!
android {
    ...
    buildFeatures {
        viewBinding true
    }
}

適当に、Viewを配置して…

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">
        <TextView
            android:id="@+id/text1"
            android:layout_margin="10dp"
            android:textSize="20sp"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="0"/>
        <TextView
            android:id="@+id/text2"
            android:layout_margin="10dp"
            android:textSize="20sp"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="0"/>
</LinearLayout>
class MainActivity : AppCompatActivity() {
    // ここで、召喚!
    private lateinit var binding: ActivityMainBinding

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        binding = ActivityMainBinding.inflate(layoutInflater)

        //bindigを付ければ、操作できる!
        binding.text1.text = "小鳥ん"
        binding.text2.text = "小鳥ん"

#####おまけ
スコープ関数を使うと毎回bindinを書かなくて良くなり、Viewが増えた時に楽。

class MainActivity : AppCompatActivity() {


    // ここで、召喚!
    private lateinit var binding: ActivityMainBinding

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        binding = ActivityMainBinding.inflate(layoutInflater)
        binding.run {
             text1.text = "小鳥ん"
             text2.text = "小鳥ん"
        }
1
0
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
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?