首页 > 解决方案 > 按下按钮状态的 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>

标签: javaandroid

解决方案


您可以尝试将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()活动或片段


推荐阅读