首页 > 解决方案 > 对 ListView 中的项目使用单个 onClickListener 时避免嵌套布局

问题描述

前提很简单。我有一个项目列表,每个项目都有一个TextView包含项目的标题,并Switch显示项目是打开还是关闭。Switch我希望能够单击项目上的任意位置来切换它,而不是点击来切换项目的打开或关闭。基本上:

<android.support.constraint.ConstraintLayout 
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:onClick="toggleSwitch">

    <TextView
        android:id="@+id/title"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>
    <Switch
        android:id="@+id/switch"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>

</android.support.constraint.ConstraintLayout>

但是,这将在屏幕中使用时创建嵌套布局,这可能对性能不利。我想知道,因为这ConstraintLayout实际上只是一个带有 的容器onClick,是否有办法以避免嵌套布局的方式实现此布局。谢谢!

标签: androidxmlandroid-layout

解决方案


您可以只为您的 textView 和您的按钮提供单击时将调用的相同方法,这样在每次视图单击(项目上的任何位置)时,您都将调用您的方法。

例如:

   textView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            //change you switch state
        }
    });

   switch.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
             //change you switch state
        }
    });

推荐阅读