android - 对 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
,是否有办法以避免嵌套布局的方式实现此布局。谢谢!
解决方案
您可以只为您的 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
}
});
推荐阅读
- python - 如何在配置文件中使用百分比存储/编码 URL?
- pyparsing - 使用 pyparsing 判断空格或数字
- linux-kernel - 新 USB 设备上的系统挂起
- python - 安装时不包含静态内容的 Python 包
- git - 还原拉取请求会在 Azure 中留下历史记录吗?
- python - 使用 HWND(窗口句柄)将应用程序嵌入到 PYQT5 GUI
- python-3.x - GNS3 2.2.23 win10上运行python 3.9.6的安装问题?
- python - cv2 安装成功后无法导入
- postgresql - 优化 postgres 查询以拉取唯一用户的前 5 条记录
- list - Flutter imagePicker 到 Uint8list