如何使用数据绑定将点击侦听器设置为 LinearLayout

How to set click listener to LinearLayout using data binding

我目前正在尝试使用数据绑定将点击侦听器设置到 .xml 布局文件中的 LinearLayout 视图。

我已经设法让它在 ButtonTextView 等其他视图上运行良好,但由于某些原因它无法在 LinearLayout.[=24 上运行=]

这是我尝试的基本内容,但我仍然无法让它工作:

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="72dp"
    android:clickable="true"
    android:focusable="true"
    android:onClick="@{action::linearLayoutClicked}"
    android:orientation="vertical">
</LinearLayout>

其中 linearLayoutClicked 是我在操作中定义的方法 class:

public void linearLayoutClicked(View view) {
    // specific logic
}

我也尝试过使用子视图以及 clickablefocusable 设置为 false 以及 duplicateParentState 设置为 true 和 [=22 的子视图=].

该操作与在其他正常工作的视图上使用的操作完全相同。

这是一个错误还是我做错了?为什么这对 LinearLayout 不起作用,但对其他视图却没有任何问题?

所以一切都设置正确,生成的绑定文件显示点击侦听器设置正确,但由于一些非常奇怪的原因,一半的绑定有效,而较新的无效。较新的意思是 LinearLayout 和围绕它的所有尝试。

解决问题的方法是简单的缓存失效和相应的重启,瞧,点击侦听器在 LinearLayout 上运行良好。请记住将其设置为 clickablefocusable 并将任何子视图设置为不可点击,这样它们就不会在父视图之前使用该事件。

您可以像下面这样处理任何视图点击事件:

  1. 创建处理点击事件的接口,如下所示:

    interface OnClickHandlerInterface {
        void onClick(View view)
    }
    
  2. 执行点击监听器class,如下所示:

    class MainActivity implements OnClickHanderInterface{
        @Override
        void OnClick(View view){
        }
    }
    
  3. 现在在XML文件中绑定这个接口:

    <data>
        <variable
            name="clickHandler"
            type=".OnClickHandlerInterface" />
    </data>
    
  4. 现在使用绑定对象注册这个接口class:

    mActivityMainBinding.clickHandler = this
    
  5. 现在在任何你想设置点击监听器的地方设置onClick。对你来说是 LinearLayout:

    <LinearLayout
        android:id="@+id/linearLayout"
        android:layout_width="match_parent"
        android:layout_height="72dp"
        android:clickable="true"
        android:focusable="true"
        android:onClick="@{(v)-> clickHandler.onClick(v)}"
        android:orientation="vertical">
    </LinearLayout>
    
  6. 现在当你的 linearLayout 点击时处理点击你可以点击在操作中实现的界面 class:

    @Override
    void OnClick(View view){
        switch(view.getId()){
        case R.id.linearLayout:
            // Handler click and do some actions
            break;
        }
    }
    
  7. 如前所述可以通过数据绑定获取布局点击

如果无效缓存不起作用。

然后 Build>Rebuild 重建 项目。修复错误(如果有)然后再次重建。