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

viewbinding步驟

binding變數

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

1
private lateinit var binding : ActivityMainBinding

inflate

綁定xml

1
binding = ActivityMainBinding.inflate(layoutInflater)

設定root

找到xml第一個元素

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
11
12
13
14
15
class MainActivity13 : AppCompatActivity() {
  // 延後初始化
  private lateinit var binding : ActivityMainBinding
  override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    binding = ActivityMainBinding.inflate(layoutInflater)
    setContentView(binding.root)
    val submit = binding.button
    val textv = binding.textView

    submit.setOnClickListener {
      textv.text = "Test, Test"
    }
  }
}

results matching ""

    No results matching ""