【问题标题】:how to change the toggle button color without a code behind如何在没有代码的情况下更改切换按钮的颜色
【发布时间】:2017-08-17 23:53:31
【问题描述】:

我使用下面的代码创建了圆形切换按钮。 我想根据切换状态更改按钮的颜色 -

如何在不向 java 活动添加代码的情况下做到这一点(类似于“textoff”和“texton”中的构建,我只能将代码添加到 xml 而无需将代码添加到后面的 java 代码)

有可能吗?

 <ToggleButton
  android:id ="@+id/actionToggleButton"
  android:layout_width="150dp"
  android:layout_height="150dp"
  android:background="@drawable/button_bg_round"
  android:textoff="off"
  android:texton="on"
  android:padding="15dp"
  />


<?xml version="1.0" encoding="utf-8"?>
 <selector xmlns:android="http://schemas.android.com/apk/res/android">
      <item>
         <shape android:shape="oval">
              <stroke android:color="#1E90FF" android:width="5dp" />
              <solid android:color="#87CEEB"/>
              <size android:width="150dp" android:height="150dp"/>
         </shape>
     </item>
 </selector>

【问题讨论】:

标签: android


【解决方案1】:

您可以在 style.xml 中为您的 ToggleButton 定义自定义样式,例如:

<style name="ToggleButton.CustomTheme" parent="Theme.AppCompat.Light">
    <item name="colorControlNormal">@color/your_color</item>
    <item name="colorControlActivated">@color/your_color</item>
</style>

然后将样式应用到您的 ToggleButton

<ToggleButton
  android:id ="@+id/actionToggleButton"
  android:layout_width="150dp"
  android:layout_height="150dp"
  android:background="@drawable/button_bg_round"
  android:textoff="off"
  android:texton="on"
  android:padding="15dp"
  android:theme="@style/ToggleButton.CustomTheme"
  />

可能是 colorAccent 而不是 colorControlActivated,我暂时无法测试。

希望这会有所帮助。

【讨论】:

    猜你喜欢
    • 2019-06-14
    • 2021-02-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-07
    • 1970-01-01
    • 2019-05-29
    相关资源
    最近更新 更多