【问题标题】:Android app: Switch images based on theme from codeAndroid 应用程序:从代码中根据主题切换图像
【发布时间】:2015-01-18 13:49:45
【问题描述】:

我试图显示一个最喜欢的按钮,它有两种状态(按下/未按下)。根据所选主题(浅色/深色),我想使用 2 组图像。

虽然我可以根据主题切换图像,但我不确定如何从代码中获取图像的 URL,以便我可以根据按钮状态显示图像。我也尝试使用选择器,但我似乎无法将 ?attr 值放入选择器以按主题切换图像。

样式定义:

<attr name="star_on_image" format="reference"/>
<attr name="star_off_image" format="reference"/>

<style name="LightTheme" parent="Theme.AppCompat.Light.DarkActionBar">
    <item name="star_on_image">@drawable/ic_action_important</item>
    <item name="star_off_image">@drawable/ic_action_not_important</item>
</style>

<style name="DarkTheme" parent="Theme.AppCompat">
    <item name="star_on_image">@drawable/ic_action_dark_important</item>
    <item name="star_off_image">@drawable/ic_action_dark_not_important</item>
</style>

按钮定义:

<ImageButton
            android:layout_width="@dimen/button_size"
            android:layout_height="@dimen/button_size"
            android:id="@+id/favorite_button_on"
            android:src="?attr/star_off_image"
            android:scaleType="center"
            android:visibility="gone"
            />

我想将此图像的 src 属性从代码切换为“?attr/star_on_image”。 关于如何做到这一点的任何想法?

【问题讨论】:

    标签: android android-resources android-theme


    【解决方案1】:

    使用这个:

    TypedValue typedValue = new TypedValue();
    getTheme().resolveAttribute(R.attr.star_on_image, typedValue, true);
    ImageButton star = ((ImageButton)findViewById(R.id.favorite_button_on));
    star.setImageResource(typedValue.resourceId);
    

    【讨论】:

      猜你喜欢
      • 2021-08-31
      • 2017-11-19
      • 1970-01-01
      • 1970-01-01
      • 2014-06-11
      • 1970-01-01
      • 2013-07-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多