【问题标题】:Not able to make a button change color ONLY while clicked (Android)仅在单击时无法使按钮更改颜色(Android)
【发布时间】:2015-07-12 20:21:01
【问题描述】:

我想要一个按钮在按下时改变颜色,然后在释放时变回原来的颜色。目前我有一个按钮,按下时可以将您带到片段。我尝试简单地使用

button.setBackgroundColor(Color.BLUE);

在按钮的 onClickListener 中,但意识到当它把我带到片段并返回活动时,按钮仍然是相同的颜色并且没有变回来。所以我的行动计划是在按下它时改变它的颜色,启动片段,然后将按钮的颜色设置为它原来的颜色,这样如果我按下按钮,它看起来就像正常(未点击)。

但是,我似乎无法在网上找到一个示例,该示例显示我将按钮的颜色作为 int 获取(因此我可以使用 setBackgroundColor(int))。有什么想法吗?

非常感谢任何帮助

【问题讨论】:

    标签: android android-fragments android-button


    【解决方案1】:

    您应该为此使用选择器 -

    创建 selector.xml(在 res/drawable 中)文件夹:

    <item android:drawable="@color/button_bg_selected" android:state_selected="true"></item>
    <item android:drawable="@color/button_bg_pressed" android:state_pressed="true"></item>
    <item android:drawable="@color/button_bg_normal"></item>
    

    `

    并将选择器设置为按钮的背景:

    <Button
     android:id="@+id/button1"
     android:background="@drawable/selector"
     android:layout_width="200dp"
     android:layout_height="126dp"
     android:text="Hello" />
    

    【讨论】:

      【解决方案2】:

      您不需要更改背景颜色,只需使用选择器。在可绘制文件夹中创建一个 xml 文件(给它一个名称,即 colour_change)。选择器有几个状态。就像在下面的代码中一样,第一部分(默认)显示没有按下按钮并聚焦,这将是颜色。第二部分显示按钮处于焦点但未按下时,而第三部分显示按钮同时处于按下和焦点时。 当你按下一个按钮时,它会改变颜色,指定它被释放的那一刻,它会返回到默认颜色状态。

      <?xml version="1.0" encoding="utf-8"?>
      <selector xmlns:android="http://schemas.android.com/apk/res/android" >
      
      
       <!-- default -->
      <item android:state_pressed="false" android:state_focused="false">
          <shape >
              <solid  android:color="#CD853F" />
           </shape>
      </item>
      
      <!-- button focused -->
      <item android:state_pressed="false" android:state_focused="true">
          <shape >
          <solid
                  android:color="#00ff00" />
           </shape>
      </item>
      <!-- button pressed -->
      <item android:state_pressed="true" android:state_focused="false">
          <shape >
              <solid
                  android:color="#00ff00" />
          </shape>
      </item> 
      

      按钮的 XML 是

      <Button
      android:id="@+id/press_button"
      android:background="@drawable/selector"
      android:layout_width="fiil_parent"
      android:layout_height="42dp"
      android:text="Press me" />
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-07-07
        • 1970-01-01
        • 1970-01-01
        • 2021-07-07
        • 1970-01-01
        • 2014-01-10
        • 2012-12-06
        相关资源
        最近更新 更多