我有一个 30px x 30px 的 png 文件,我想将其用作 android:src 而不是 android:background。通过使用它作为背景,并在高度和宽度上都提到“wrap_content”,最终结果看起来更像是 45 像素 x 45 像素。
理想情况下,我需要的是 ImageButton 和 ToggleButton 的组合。我希望具有设置 ImageButton 的 android:src 的功能以及为我自动保存状态的切换功能。
任何解决方案或解决方法?
TIA。
您好,这似乎对创建另一种样式没有帮助。 src 看起来仍然比原来的 30px x 30px 大得多。
在 main.xml 中:
<ToggleButton android:id="@+id/blah"
style="@style/myToggle"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
</ToggleButton>
在 Styles.xml 中
<style name="myToggle">
<item name="android:textOn">""</item>
<item name="android:textOff">""</item>
<item name="android:disabledAlpha">?android:attr/disabledAlpha</item>
<item name="android:background">@drawable/my_btn_toggle_bg</item>
</style>
在 my_btn_toggle_bg.xml 中
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="@+id/myBackground" android:drawable="@android:drawable/btn_default_small" />
<item android:id="@+id/myToggle" android:drawable="@drawable/my_btn_toggle" />
</layer-list>
在 my_btn_toggle.xml 中
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_checked="false" android:drawable="@drawable/pausebutton" />
<item android:state_checked="true" android:drawable="@drawable/playbutton" />
</selector>
playbutton.png 和 pausebutton.png 都是 30px x 30px。但是当我看到它在设备上的布局时,它们显得更大
最佳答案
您可以使切换按钮看起来像任何您想要的样子。您只需要创建一种样式。查看/platforms//data/res/values/styles.xml 并搜索 Widget.Button.ToggleButton 它看起来像这样:
<style name="Widget.Button.Toggle">
<item name="android:background">@android:drawable/btn_toggle_bg</item>
<item name="android:textOn">@android:string/capital_on</item>
<item name="android:textOff">@android:string/capital_off</item>
<item name="android:disabledAlpha">?android:attr/disabledAlpha</item>
</style>
因此,如果您找到 btn_toggle_bg 可绘制对象,您会发现:
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="@+android:id/background" android:drawable="@android:drawable/btn_default_small" />
<item android:id="@+android:id/toggle" android:drawable="@android:drawable/btn_toggle" />
</layer-list>
这表明它使用标准的 Button
背景和一个名为 btn_toggle 的 drawable 作为 src。 btn_src.xml 看起来像这样:
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_checked="false" android:drawable="@drawable/btn_toggle_off" />
<item android:state_checked="true" android:drawable="@drawable/btn_toggle_on" />
</selector>
这是用来显示按钮状态的两个drawable。它们实际上称为 btn_toggle_{on/off}.9.png,因为它们是 9 个补丁图像,因此它们会拉伸(stretch)以匹配按钮大小。
关于android - 为 ToggleButton 设置图像源,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6100034/