【问题标题】:change Image Button System Resource when clicked单击时更改图像按钮系统资源
【发布时间】:2013-06-15 23:27:35
【问题描述】:

我想改变例如btn_star_big_off 到 btn_star_big_on

每次有人点击按钮时,按钮的状态都会改变。 Toogle 将是完美的,但我不知道如何将其结合起来。而且我不知道如何更改按钮的状态。我发现我可以使用可绘制的 XML 文件来做到这一点,但是我只能访问我导入的图像,但不能访问系统资源的图像?

按钮:

<ImageButton
                android:id="@+id/imageButton4"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:src="@android:drawable/btn_star_big_off" />

这是我的可绘制 XML 的试用版:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">

    <item android:drawable="@drawable/button" android:state_pressed="true"/>
 <!-- pressed -->
    <item android:drawable="@drawable/button"/>
 <!-- default -->

</selector>

【问题讨论】:

  • 尝试以编程方式更改视图的 onclick 事件。

标签: java android button click


【解决方案1】:

你需要使用切换按钮

1) 在您的布局中,实现 ToggleButton

<TableRow
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:weightSum="1">

    <ToggleButton
    android:layout_width=0dp"
    android:layout_height="wrap_content"
    android:layout_weight=".3"
    android:background="@drawable/my_button"
    android:text=""
    android:textOff=""
    android:textOn=""/>

</TableRow>

2) 在可绘制目录中创建 xml 布局(此处为 my_button.xml)

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@android:drawable/btn_star_big_on" android:state_pressed="true"/><!-- pressed -->
    <item android:drawable="@android:drawable/btn_star_big_on" android:state_focused="true"/><!-- focused -->
    <item android:drawable="@android:drawable/btn_star_big_on" android:state_checked="true"/>
    <item android:drawable="@android:drawable/btn_star_big_off" android:state_checked="false"/>
    <item android:drawable="@android:drawable/btn_star_big_off"/> <!-- default -->
</selector>

在这里我添加另一个状态,如果你想有一个专注的 img

【讨论】:

  • 谢谢!这有很大帮助,但仍然存在问题。当我这样做时,我收到一个错误:错误:错误:找不到与给定名称匹配的资源(在'drawable',值为'@drawable/btn_star_big_off')。因为我没有在我的电脑上保存图像,所以它们来自 android(来自系统资源)。如何响应系统资源图像?
  • 没问题!我的代码已被编辑。如果你没问题,请点击:)
  • 很抱歉再次打扰您,但现在我又遇到了两个问题:第一个是 ON 和 OFF 在我的符号前面显示为文本。第二个是图像被缩放,但我想要它的原始大小。你对我有什么建议吗:-) 这就是dl.dropboxusercontent.com/u/20731482/star.jpg 的样子
  • 没问题我的朋友!我用文本、textOn 和 textOff 为 toggleButton 更新了我的切换按钮。您是否在 togglebutton 上添加 layout_width="wrap_content" (并且没有 match_parent )?
  • 现在 ToggleBUtton 减少 match_parent 总宽度的 30% ( .3 = 30% , .1 = 10% )
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-11-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-04-14
相关资源
最近更新 更多