【问题标题】:How to add custom item in android Theme declaration?如何在 android Theme 声明中添加自定义项?
【发布时间】:2017-02-11 02:10:53
【问题描述】:

我的 styles.xml 中几乎没有自定义主题
现在,每当活动采用主题时,它都会使用 colorPrimarycolorPrimaryDarkcolorAccent 值。
对于我的布局背景,我使用 ?attr/colorAccent,因此它可以根据所选主题选择背景颜色。
如果我使用上述任何值,它都可以正常工作。但我想为我的背景颜色定义一个自定义项目值。
我在下面尝试过这样的方法,但没有奏效。有什么想法让它发挥作用吗?
我具有自定义值的自定义主题:

<style name = "customTheme" parent="Theme.AppCompat.Light.NoActionBar">
    <item name="colorPrimary">#4285f4</item>
    <item name="colorPrimaryDark">#2C75F2</item>
    <item name="colorAccent">#E1FFC7</item>
    <item name="customBgColor">#d3d3d3</item>
</style>


我想在布局样式中使用它作为

<style name="layoutStyle" >
    <item name="android:background">?attr/customBgColor</item>
</style>

【问题讨论】:

    标签: android android-theme android-styles


    【解决方案1】:

    创建一个attrs.xml 文件,如图所示。

    <?xml version="1.0" encoding="utf-8"?>
    <resources>
    
       <!-- Other values-->
       <attr name="customBgColor" format="reference" />
    
    </resources>
    

    自定义主题 1

    <style name = "customTheme1" parent="Theme.AppCompat.Light.NoActionBar">
        <!-- Other values-->
        <item name="customBgColor">#d3d3d3</item>
    </style>
    

    自定义主题 2

    <style name = "customTheme2" parent="Theme.AppCompat.Light.NoActionBar">
        <!-- Other values-->
        <!-- Black Color in theme2-->
        <item name="customBgColor">#111111</item>
    </style>
    

    例如将颜色设置为TextView

    您可以在任何地方的任何小部件中以类似的方式使用它。

    TextView 用于以下活动。

    <TextView
        android:id="@+id/txt_rate_us_about"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:text="Rate us on Play Store!"
        android:textColor="?attr/customBgColor"
        android:textSize="20dp" />
    

    想动态设置主题。

    public class AboutUsActivity extends Activity {
    
        int theme = 1;
        // int theme = 2;  2nd theme.
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            // TODO Auto-generated method stub
            super.onCreate(savedInstanceState);
            switch (theme) {
                default:
                case 1:
                    this.setTheme(R.style.customTheme1);
                    break;
                case 2:
                    this.setTheme(R.style.customTheme2);
                    break;
    
            }
            // you must call `setTheme()` before `setContentView()`
            setContentView(R.layout.activity_about);
    
        }
    

    对于多个活动,您分别为每个活动设置了主题。

    【讨论】:

    • 我错过了定义属性,添加 attrs.xml 后,它工作正常。谢谢@sohail。
    • 而不是在项目内放置颜色代码。将其放入 color.xml 并将该颜色标签添加到 item..
    猜你喜欢
    • 2019-02-26
    • 1970-01-01
    • 2018-07-05
    • 2022-01-20
    • 2020-03-04
    • 2015-10-27
    • 2017-05-25
    • 2015-10-02
    • 2020-10-24
    相关资源
    最近更新 更多