如何在android主题声明中添加自定义项?

Shr*_*ree 10 android android-theme android-styles

我在styles.xml中有很少的自定义主题
现在每当活动采用主题时,它都使用colorPrimary,colorPrimaryDarkcolorAccent值.
对于我的布局背景我正在使用?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>
Run Code Online (Sandbox Code Playgroud)


我想在布局的风格中使用它

<style name="layoutStyle" >
    <item name="android:background">?attr/customBgColor</item>
</style>
Run Code Online (Sandbox Code Playgroud)

Soh*_*hid 22

创建attrs.xml图像中显示的文件.

<?xml version="1.0" encoding="utf-8"?>
<resources>

   <!-- Other values-->
   <attr name="customBgColor" format="reference" />

</resources>
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

customTheme 1

<style name = "customTheme1" parent="Theme.AppCompat.Light.NoActionBar">
    <!-- Other values-->
    <item name="customBgColor">#d3d3d3</item>
</style>
Run Code Online (Sandbox Code Playgroud)

customTheme 2

<style name = "customTheme2" parent="Theme.AppCompat.Light.NoActionBar">
    <!-- Other values-->
    <!-- Black Color in theme2-->
    <item name="customBgColor">#111111</item>
</style>
Run Code Online (Sandbox Code Playgroud)

将颜色设置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" />
Run Code Online (Sandbox Code Playgroud)

想要动态设置主题.

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);

    }
Run Code Online (Sandbox Code Playgroud)

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