java - 按下按钮状态的 ConstraintLayout
问题描述
我有一个复杂的按钮,但可以使用约束布局轻松完成。但是,我希望按钮状态更改功能可以在按下时更改背景颜色。我尝试使用 state press 或 selected,但它不起作用。解决这个问题的最佳方法是什么?
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_pressed="true" android:drawable="@drawable/button_pressed"/>
<item android:state_pressed="false" android:drawable="@drawable/button_grayout" />
</selector>
ConstraintLayout 作为按钮
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:layout_marginEnd="16dp"
android:background="@drawable/button_press"
android:id="@+id/background_create"
android:padding="8dp">
<TextView
android:id="@+id/txt_display"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Big Text"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="#ffffff"
android:textStyle="bold"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Mini Text"
android:textAppearance="?android:attr/textAppearanceSmall"
android:textColor="#D5D5D5"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toBottomOf="@+id/txt_display_alert1" />
</androidx.constraintlayout.widget.ConstraintLayout>
解决方案
您可以尝试将onClick
事件添加到 ConstraintLayout,如下所示:
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:layout_marginEnd="16dp"
android:background="@drawable/button_press"
android:id="@+id/background_create"
android:padding="8dp"
android:onClick="onClick"
>
....
添加onClick()
活动或片段
推荐阅读
- c - 删除结束行字符
- reactjs - 无法从表单接收数据
- apache-spark - Apache/Cloudera HUE / Livy Spark Server - InterpreterError: 无法启动解释器
- git - 通过特定提交将 git 更改从一个分支隔离到另一个分支
- optimization - 基于变量在阶跃函数中生成值
- node.js - 为什么 MongoDB 为该模式中不存在的字段创建索引?
- python - 从 Pandas DataFrame 创建 Spark DataFrame
- azure-language-understanding - 无法映射到 personName 预建实体
- aframe - 如何跟踪实体上的光线投射相交坐标?
- azure-cosmosdb - Cosmos DB Sql如何获取数组中不同的项目列表?