为什么我的ImageButton样式没有应用到我的ImageButton上?

3

我可以帮你进行翻译。这段内容涉及到 IT 技术,包含了样式设置和 API 版本控制的问题。其中 ImageButton 的样式出现了问题。

v-21 版本的样式如下:

<style name="BorderlessImageButton" parent="AppTheme.BorderlessImageButton">
    <item name="android:background">?android:attr/selectableItemBackgroundBorderless</item>
    <item name="android:tint">@color/secondary_text</item>
</style>

所有21版本以下的API将使用以下样式:
<style name="BorderlessImageButton" parent="AppTheme.BorderlessImageButton"/>

<style name="AppTheme.BorderlessImageButton" parent="@android:style/Widget.ImageButton">
    <item name="android:tint">@color/secondary_text</item>
    <item name="android:background">@color/borderless_button_background</item>
</style>

这是我的XML资源。
<ImageButton
    android:id="@+id/imageButton"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_centerVertical="true"
    android:layout_toStartOf="@id/date_picker"
    android:background="@null"
    android:padding="10dp"
    android:src="@drawable/ic_today_white_24dp"
    android:theme="@style/BorderlessImageButton" />

如果我在使用v-21或v-22的设备上运行此代码,使用?android:attr/selectableItemBackgroundBorderless时按钮没有按照我期望的方式对我的触摸做出视觉反应。而且,在任何低于v-21的设备上,该按钮仍然不会对我设置的选择器资源做出反应。
res/color/borderless_button_background.xml:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_pressed="true" android:color="@color/accent" />
    <item android:color="@color/transparent"/>
</selector>

请帮我让按钮根据用户设备上的API正确响应触摸操作。

谢谢


您可以使用style="@style/BorderlessImageButton"来应用自定义样式,而android:theme则用于活动。 - Gil Vegliach
1
天啊,就是这样。把它作为答案吧!我会标记它为正确的。 - hellaandrew
完成。我还附上了文档链接,这也会有所帮助 :-) - Gil Vegliach
1
非常感谢。我已经理解了如何为视图设置样式,但似乎我一直没有正确应用它。 - hellaandrew
1个回答

2

您需要使用以下方式应用样式:

style="@style/BorderlessImageButton"

属性 android:theme 用于活动(activities),请查看这里

更新

从Android 5.0或使用AppCompat 22.1.0+(API 11+)开始,您还可以使用ThemeOverlay并在单个视图上使用android:theme。您可以在这里了解此技术。感谢Ian提供的信息。


1
实际上,您可以像这个专业提示中所解释的那样,在单个视图上使用android:theme。但是,这些不使用样式,而是理想情况下使用ThemeOverlay,更接近于活动样式模型。 - ianhanniballake
谢谢,我把它放在答案里供未来读者参考。我还在博客文章中加了一个小评论。 - Gil Vegliach

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接