[Android Studio|Kotlin] Binding 
Published: 2022-02-20 20:39:16

**viewBinding**

```
    buildFeatures {
        viewBinding = true
    }
```

**Example 1 ) setOnClickListener**

[MainActivity.kt]
```
class MainActivity : AppCompatActivity() {

    val binding by lazy { ActivityMainBinding.inflate(layoutInflater) }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(binding.root)

        binding.btnSay.setOnClickListener {
            binding.textSay.text = "Hello Kotlin"
        }

    }
}
```

[activity_main.xml]

```
    <TextView
        android:id="@+id/textSay"
        android:layout_width="77dp"
        android:layout_height="19dp"
        android:text="Hello World!"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <Button
        android:id="@+id/btnSay"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="31dp"
        android:text="Button"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/textSay" />
```

**Example 2-1 ) addTextChangedListener**
[activity_main.xml] 
``` 
    <TextView
        android:id="@+id/textView"   />

    <EditText
        android:id="@+id/editText" />
```


```
class MainActivity : AppCompatActivity() {

    val binding by lazy { ActivityMainBinding.inflate(layoutInflater) }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(binding.root)

        with(binding) {
            editText.addTextChangedListener{
                Log.d("EditText012345", "Current Value=${it.toString()}")
            }
        }
    }
}
```

**Example 2-2 ) addTextChangedListener**
[MainActivity.kt]

```
class MainActivity : AppCompatActivity() {

    val binding by lazy { ActivityMainBinding.inflate(layoutInflater) }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(binding.root)

        with(binding) {
            editText.addTextChangedListener{ editable ->
                Log.d("EditText012345", "Current Value=${editable.toString()}")
            }
        }
    }
}
```
 
**Example 2-3 ) addTextChangedListener**
_Depending on the version of Android Studio used, the parameters of the automatically generated function may be different. 
like .. **[s: Editable?], [s: CharSequence?], [p0: Editable?], [edit: Editable?]**_

[MainActivity.kt]
```
class MainActivity : AppCompatActivity() {

    val binding by lazy { ActivityMainBinding.inflate(layoutInflater) }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(binding.root)

        binding.editText.addTextChangedListener(object : TextWatcher{
            override fun beforeTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {
            }
            override fun onTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {
            }
            override fun afterTextChanged(p0: Editable?) {
                Log.d("EditText012345", "Current Value=${p0.toString()}")
                binding.textView.text = p0.toString()
            }
        })
    }
}
``` 

**Example 3-1 ) _Check if the entered characters are 8 or more characters like when checking ID when logging in_**
[MainActivity.kt]

```

class MainActivity : AppCompatActivity() {

    val binding by lazy { ActivityMainBinding.inflate(layoutInflater) }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(binding.root)

        with(binding) {
            editText.addTextChangedListener{
                if (it.toString().length >= 8) {
                    Log.d("EditText012345", "over 8=${it.toString()}")
                }
            }
        }
    }
}
```

**Example 3-2 ) _Check if the entered characters are 8 or more characters like when checking ID when logging in_**
[MainActivity.kt]

``` 
class MainActivity : AppCompatActivity() {

    val binding by lazy { ActivityMainBinding.inflate(layoutInflater) }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(binding.root)

        binding.editText.addTextChangedListener(object : TextWatcher{
            override fun beforeTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {
            }
            override fun onTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {
            }
            override fun afterTextChanged(p0: Editable?) {
                if (p0.toString().length >= 8 ) {
                    Log.d("EditText012345", "over 8=${p0.toString()}")
                }
            }
        })
    }
}
```

**Example 4-1 ) CHECKBOX**
_{ compoundButton, b -> }
{ compoundButton, i -> }
{ buttonView, isChecked -> }_

[MainActivity.kt]

```
class MainActivity : AppCompatActivity() {

    val binding by lazy { ActivityMainBinding.inflate(layoutInflater) }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(binding.root)

        with(binding) {
            checkApple.setOnCheckedChangeListener (listener)
            checkBanana.setOnCheckedChangeListener (listener)
            checkOrange.setOnCheckedChangeListener (listener)
        }
    }
    var listener = CompoundButton.OnCheckedChangeListener { buttonView, isChecked ->
        if (isChecked) {
            when (buttonView.id) {
                R.id.checkApple -> Log.d("CheckBox", "Apples have been selected.")
                R.id.checkBanana -> Log.d("CheckBox", "Banana have been selected.")
                R.id.checkOrange -> Log.d("CheckBox", "Orange have been selected.")
            }
        } else {
            when (buttonView.id) {
                R.id.checkApple -> Log.d("CheckBox", "Apple are deselected.")
                R.id.checkBanana -> Log.d("CheckBox", "Banana are deselected.")
                R.id.checkOrange -> Log.d("CheckBox", "Orange are deselected.")
            }
        }
    }
}
```
**Example 4-2 ) CHECKBOX**
{ compoundButton, b -> }
{ buttonView, isChecked -> }
[MainActivity.kt]

```
class MainActivity : AppCompatActivity() {

    val binding by lazy { ActivityMainBinding.inflate(layoutInflater) }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(binding.root)

        with(binding) {
            var listener = CompoundButton.OnCheckedChangeListener { compoundButton, b -> 
                if (b) {
                    when (compoundButton.id) {
                        R.id.checkApple -> Log.d("CheckBox", "Apples have been selected.")
                        R.id.checkBanana -> Log.d("CheckBox", "Banana have been selected.")
                        R.id.checkOrange -> Log.d("CheckBox", "Orange have been selected.")
                    }
                } else {
                    when (compoundButton.id) {
                        R.id.checkApple -> Log.d("CheckBox", "Apple are deselected.")
                        R.id.checkBanana -> Log.d("CheckBox", "Banana are deselected.")
                        R.id.checkOrange -> Log.d("CheckBox", "Orange are deselected.")
                    }
                }
            }
            checkApple.setOnCheckedChangeListener (listener)
            checkBanana.setOnCheckedChangeListener (listener)
            checkOrange.setOnCheckedChangeListener (listener)
        }

    }
}
```
**Example 5 ) ToggleButton, Switch**
[MainActivity.kt]

```
class MainActivity : AppCompatActivity() {

    val binding by lazy { ActivityMainBinding.inflate(layoutInflater) }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(binding.root)

        with(binding) {
            toggleButton.setOnCheckedChangeListener { compoundButton, isChecked ->
                textToggle.text = if(isChecked) "On" else "Off"
            }
            switchButton.setOnCheckedChangeListener { compoundButton, isChecked ->
                textSwitch.text = if(isChecked) "On" else "Off"
            }
        }
    }
}
```

**Example 6 ) ProgressBar**
_LinearLayout android:id="@+id/progressLayout"_
[MainActivity.kt]

```
class MainActivity : AppCompatActivity() {

    val binding by lazy { ActivityMainBinding.inflate(layoutInflater) }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(binding.root)

        with(binding) {
            // MAIN THREAD
            showProgress(true)
            thread(start=true) {
                Thread.sleep(3000)
                runOnUiThread {
                    showProgress(false)
                }
            } // SUB THREAD
        } // MAIN THREAD
    }

    fun showProgress(show: Boolean){
        binding.progressLayout.visibility = if(show) View.VISIBLE else View.GONE
    }
}
```


**Example 7 ) SeekBar**
_SeekBar android:id="@+id/seekBar"
TextView android:id="@+id/textView"_
(SeekBar: SeekBar?, progress: Int, fromUser: Boolean) 
(p0: SeekBar?, p1: Int, p2: Boolean) 
[MainActivity.kt]

```
class MainActivity : AppCompatActivity() {

    val binding by lazy { ActivityMainBinding.inflate(layoutInflater) }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(binding.root)

        with(binding) {
            seekBar.setOnSeekBarChangeListener(object :SeekBar.OnSeekBarChangeListener {
                override fun onProgressChanged(p0: SeekBar?, p1: Int, p2: Boolean) {
                    textView.text = "$p1"
                }
                override fun onStartTrackingTouch(p0: SeekBar?) {}
                override fun onStopTrackingTouch(p0: SeekBar?) {}
            })
        }
    }
}

```

**Example 8 ) Rating Bar** 
RatingBar android:id="@+id/ratingBar"
TextView android:id="@+id/textView"
{ ratingBar, fl, b -> }
{ ratingBar, rating, fromUser -> }
[MainActivity.kt]
``` 

class MainActivity : AppCompatActivity() {

    val binding by lazy { ActivityMainBinding.inflate(layoutInflater) }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(binding.root)

        with(binding) {
            ratingBar.setOnRatingBarChangeListener { ratingBar, fl, b ->
                textView.text = "$fl"
            }
        }
    }
}
```