7
2

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 5 years have passed since last update.

Kotlin×DataBindingで「アイエエエ onClick() 呼ばれないナンデ?!?!」となったときに確認すること

Posted at

凡ミスをやってしまったので備忘メモ。👾

DataBindingでonClick()実装

activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools">

    <data>

        <variable
            name="owner"
            type="com.shanonim.sample.MainActivity" />
    </data>

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">

        <Button
            android:id="@+id/button"
            android:layout_width="200dp"
            android:layout_height="wrap_content"
            android:onClick="@{() -> owner.onClickButton()}"
            android:text="@android:string/ok" />
    </RelativeLayout>
</layout>

クラス側でonClickButton()を書いてあげると、タップ時にメソッドが実行されます。

fun onClickButton() {
    Toast.makeText(this, "tapped", Toast.LENGTH_SHORT).show()
}

onClick()が呼ばれない...😢

下記の実装では、ボタンをタップしてもonClickButton()が呼ばれません。

MainActivity.kt
class MainActivity : Activity() {

    var binding: ActivityMainBinding? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = DataBindingUtil.setContentView(this, R.layout.activity_main)
    }

    ...

【解決策】binding!!.○○ = thisを忘れない🙅

xml側の<variable>で指定しているnameとViewを紐付けてあげないといけません。

<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools">

    <data>

        <variable
            name="owner"
            type="com.shanonim.sample.MainActivity" />
    </data>

であれば、

binding!!.owner = this

が必要です。

先ほどのActivityのコードを補足してみます。

class MainActivity : Activity() {

    var binding: ActivityMainBinding? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = DataBindingUtil.setContentView(this, R.layout.activity_main)
        binding!!.owner = this
    }

    ...

これで無事にボタンがタップできるようになりました🎉

7
2
2

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
7
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?