LoginSignup
1
1

More than 3 years have passed since last update.

Databindingで下に重なっているViewにタッチイベントを送らないようにする

Posted at

タイトル以上でも以下でもないので、早速本題に

BindingAdapterの定義

ViewBinding.kt
@BindingAdapter("app:touch_block")
fun setTouchBlock(view: View, isBlock: Boolean) {
    view.setOnTouchListener { _, _ -> isBlock }
}

onTouch の戻り値をレイアウトから指定できるようにする

レイアウトでの指定方法

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

    <android.support.constraint.ConstraintLayout
        android:id="@+id/upper_layout"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:touch_block="@{true}"    //  ココ
        ...

これで id/upper_layout の下に重なっているViewにタッチイベントが送られなくなりました。
細かい条件は指定できないので割り切りでタッチイベントを送りたくないという場合には使えそう。

app:touch_block="@{true}"app:touch_block="@{viewModel.touchBlock}" とすればアプリの状態に応じてタッチイベントを 送る/送らない くらいの制御はできそうです。

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

    <data>
        <variable
            name="viewModel"
            type="com.hoge.SampleViewModel" />
    </data>

    ...

    <android.support.constraint.ConstraintLayout
        android:id="@+id/upper_layout"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:touch_block="@{viewModel.touchBlock}"    //  ココ
        ...
SampleViewModel.kt
SampleViewModel : ViewModel() {
    val touchBlock = ObservableBoolean(true)

...
}
1
1
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
1