gpt4 book ai didi

android - 定义特定的 View 样式以在主题内部使用

转载 作者:行者123 更新时间:2023-11-30 02:48:43 25 4
gpt4 key购买 nike

我想为一个应用程序添加多个主题,可以通过编程方式选择。

如何为这些主题中的特定 View 定义样式?

假设我有一个在 my_layout.xml 中显示 Logo 的 ImageView:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
/>

<ImageView
android:layout_width="250dp"
android:layout_height="250dp"

android:layout_centerHorizontal="true"
android:layout_centerVertical="true"

android:src="@drawable/ic_logo"
android:contentDescription="@string/app_name"
/>
<!-- ...other views... -->
</RelativeLayout>

如何更改主题的 ImageView 的 src

有没有办法为主题定义自定义元素,以便我可以将其应用于特定 View ?

类似于:

<resources xmlns:android="http://schemas.android.com/apk/res/android">

<style name="MyTheme" parent="android:Theme.Holo.Light">
<item name="logoImageView">@style/baseLogoImageView</item>
</style>

<style name="baseLogoImageView">
<item name="android:src">@drawable/ic_logo</item>
</style>

</resources>

然后在my_layout.xml中使用它:

...
<ImageView style="@style/logoImageView"
...

上面的例子没有用;我遗漏了什么或者不可能达到那个结果?

提前致谢。

最佳答案

我自己根据 this answer 找到了解决方案:

声明属性以用作样式引用:

<declare-styleable name="CustomThemeViews">
<attr name="myViewStyle" format="reference"/>
</declare-styleable>

为每个主题定义样式:

<style name="myViewStyleTheme01">
<item name="android:background">#f00</item>
</style>

<style name="myViewStyleTheme02">
<item name="android:background">#0f0</item>
</style>

定义引用不同风格的主题:

<style name="AppTheme" parent="android:Theme.Light">
<item name="myViewStyle">@style/myViewStyleTheme01</item>
</style>

<style name="AppThemeAlternative" parent="android:Theme.Light">
<item name="myViewStyle">@style/myViewStyleTheme02</item>
</style>

在布局中使用主题样式

<ListView style="?attr/myViewStyle"
android:layout_width="match_parent"
android:layout_height="match_parent"
...

现在,应用于 ListView 的样式会根据应用的主题而变化。

关于android - 定义特定的 View 样式以在主题内部使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24578576/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com