【问题标题】:Why isn't my ImageButton style being applied to my ImageButton?为什么我的 ImageButton 样式没有应用到我的 ImageButton?
【发布时间】:2015-12-13 00:25:46
【问题描述】:

我设置了一些样式来处理不同的 API(一种用于 v21,另一种用于低于此的任何 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>

将用于 v-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是为了活动
  • 天哪,就是这样。把它作为一个答案,伙计!我将其标记为正确
  • 完成。我还放了一个文档链接,这也有帮助:-)
  • 非常感谢。我一直在思考这样的样式视图,但似乎我没有正确应用它。

标签: android android-styles


【解决方案1】:

你需要应用你的风格

style="@style/BorderlessImageButton"

属性android:theme用于活动,见this


更新

从 Android 5.0 开始,或使用 AppCompat 22.1.0+ (api 11+),您还可以在单​​个视图上使用 ThemeOverlayandroid:theme。您可以阅读有关此技术的信息here。感谢 Ian。

【讨论】:

  • 事实上,您可以在单个视图上使用android:theme,如this pro-tip 中所述。但是,那些不使用样式,但理想情况下是ThemeOverlay,它更接近于活动样式的模型。
  • 谢谢,我把它放在未来读者的答案中。我还在博文中发表了一个小评论。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-04-25
  • 1970-01-01
  • 2013-05-06
  • 1970-01-01
相关资源
最近更新 更多