【问题标题】:Change FloatingActiongButton background and image color when clicked单击时更改浮动操作按钮的背景和图像颜色
【发布时间】:2021-03-11 12:21:12
【问题描述】:

我想做this layout 在 Android 中,当单击按钮时,我想更改背景颜色。

目前在我有app:backgroundTint="@color/white"的XML中, 但是当我单击按钮时,我希望背景颜色变为蓝色,并且检查符号颜色变为白色。

【问题讨论】:

    标签: android floating-action-button


    【解决方案1】:

    您可以使用选择器而不是单一颜色,可能基于选中状态,然后在单击按钮时设置选中状态。


    您的选择器可能如下所示:

    <selector xmlns:android="http://schemas.android.com/apk/res/android" >
        <item
            android:color="hex_color"
            android:state_checked=["true" | "false"] />
    
        <item android:color="hex_color" />
    </selector>
    

    【讨论】:

      【解决方案2】:

      使用自定义复选框需要三个xml。

      1. button_background.xml : 用于根据按钮检查状态改变背景
      2. tick_button_checked.xml:选中状态按钮可绘制
      3. tick_button_unchecked.xml:未选中状态按钮可绘制

      tick_button_unchecked.xml

      <?xml version="1.0" encoding="utf-8"?>
      <layer-list xmlns:android="http://schemas.android.com/apk/res/android">
          <item>
              <shape android:shape="oval">
                  <solid android:color="#ffffff" />
                  <size
                      android:width="48dp"
                      android:height="48dp" />
              </shape>
          </item>
      
          <item android:drawable="@drawable/ic_check_grey" />
      
      </layer-list>
      

      tick_button_checked.xml

      <?xml version="1.0" encoding="utf-8"?>
      <layer-list xmlns:android="http://schemas.android.com/apk/res/android">
          <item>
              <shape android:shape="oval">
                  <solid android:color="#3f43b4" />
                  <size
                      android:width="48dp"
                      android:height="48dp" />
              </shape>
          </item>
      
          <item android:drawable="@drawable/ic_check_white" />
      
      </layer-list>
      

      button_background.xml

      <?xml version="1.0" encoding="utf-8"?>
      <selector xmlns:android="http://schemas.android.com/apk/res/android">
          <item android:drawable="@drawable/tick_button_checked" android:state_checked="true" />
          <item android:drawable="@drawable/tick_button_unchecked" android:state_checked="false" />
      </selector>
      

      activity_main.xml 中的复选框按钮

          <CheckBox
              android:id="@+id/checkbox"
              android:layout_width="48dp"
              android:layout_height="48dp"
              android:background="@drawable/button_background"
              android:button="@android:color/transparent"
              android:checked="false" />
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2014-10-09
        • 2017-08-02
        • 2014-10-10
        • 2017-03-27
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多