Activity ViewBinding

build.gradle設置

app下的build.gradle設置以下內容,設置完後一定要同步Sync

1
2
3
4
5
6
7
android {
    ...

    buildFeatures {
        viewBinding = true
    }
}

import

1
import com.example.coroutine.databinding.ActivityMainBinding

binding檔案

Binding 類名直接對應 Layout 檔案名:

Binding 類 對應的 Layout 檔案
ActivityMainBinding activity_main.xml
FragmentMyBinding fragment_my.xml
ItemListBinding item_list.xml
DialogCustomBinding dialog_custom.xml

命名規則: 移除底線 _

駝峰命名法(每個單字首字母大寫)

結尾加上 Binding

binding放置位置

要先Run > Run app 才會在app目錄下產生 build 目錄。

img

Activity viewbinding步驟

binding變數

lateinit是延後初始化,就不用給binding先設值。

1
private lateinit var binding : ActivityMainBinding

inflate 取得binding

1
binding = ActivityMainBinding.inflate(layoutInflater)

點擊layoutInflater就會導到Activity中getLayoutInflater()方法。

1
2
3
4
5
6
7
8
9
10
public class Activity {
...
    public final LayoutInflater getLayoutInflater() {
        if (mLayoutInflater == null) {
            return performGetLayoutInflater(null);
        }
        return mLayoutInflater;
    }
...
}

設定layout

root就是ActivityMainBinding的getRoot()的方法,找到xml第一個元素,取得view。

1
setContentView(binding.root)

androidx.constraintlayout.widget.ConstraintLayout就是root。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
<androidx.constraintlayout.widget.ConstraintLayout 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:id="@+id/main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".activity.MainActivity07">

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="0"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Add"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/textView" />

</androidx.constraintlayout.widget.ConstraintLayout>

使用元件

1
binding.textView.text = "Test"

完整程式碼

1
2
3
4
5
6
7
8
9
10
class MainActivity13 : AppCompatActivity() {
  // 延後初始化
  private lateinit var binding : ActivityMainBinding
  override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    binding = ActivityMainBinding.inflate(layoutInflater)
    setContentView(binding.root)
    binding.textView.text = "Test, Test"
  }
}

results matching ""

    No results matching ""