如何为布局设置不同的主题

时间:2013-08-29 09:52:27

标签: android user-interface styles themes android-linearlayout

我为整个应用设置了默认主题。它在styles.xml中定义如下:

    <style name="DefaultTheme" parent="@android:style/Theme.Holo.Light">
        <!-- Customization here -->
    </style>

我还定义了一个黑暗的主题:

    <style name="DarkTheme" parent="@android:style/Theme.Holo">
        <!-- Customization here -->
    </style>

在清单中,它被宣布为灯光主题作为应用的主题:

    <application
    ...
    android:theme="@style/DefaultTheme" >

现在这个工作正常,但在一个活动中,我需要为单个布局设置不同的主题。像这样:

    +--------------------------------------------------+
    |         Parent Linear layout (default theme)     |
    |                                                  |
    | +------------------------------------+ +-------+ |
    | |                                    | |       | |
    | |     Left linear layout             | |       | |
    | |     (default theme)                | |       | |
    | |                                    | |       | |
    | |                                    | |       | |
    | |                                    | |    ·<----------- Right Linear Layout
    | |                                    | |       | |        (Need it in dark theme)
    | |                                    | |       | |
    | |                                    | |       | |
    | +------------------------------------+ +-------+ |
    +--------------------------------------------------+

在布局xml文件中,我正在尝试为最右边的子项LinearLayout设置主题:

    <LinearLayout
    style="@style/DarkTheme">
    ...

我希望这个工作得很好,并且只将黑暗主题应用于正确的布局(及其子视图),但它不起作用。我尝试用内置的@android:样式替换@style无济于事。我已经在布局编辑器和真实设备/模拟器上测试过它。

是否可以将自定义主题或样式应用于单个布局?

5 个答案:

答案 0 :(得分:28)

现在可以通过在视图上使用android:theme属性并将其设置为您喜欢的任何主题来实现。请注意,子视图将继承其父级的主题。

答案 1 :(得分:11)

在以编程方式创建布局时,您可以使用ContextThemeWrapper()来应用主题。

LinearLayout darkThemeLayout = new LinearLayout(new ContextThemeWrapper(context, R.style.DarkTheme));

答案 2 :(得分:5)

使用支持库,您可以:

app:theme="R.style.MyTheme"

答案 3 :(得分:1)

API 24添加了基于视图的主题参数,但需要棉花糖或更高版本。
另一种选择是使用android支持库以获得最大的兼容性。

设置视图的支持库的主题参数

<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    ...
>
    <LinearLayout
        app:theme="R.style.MyTheme"
        ...
    >
        <!-- content-->
    </LinearLayout>
...
</LinearLayout>

引用了在资源xml中定义为样式的主题

<resources>
    <style name="MyTheme">
        <item name="colorPrimary">@color/colorPrimary</item>
        <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
        <item name="colorAccent">@color/colorAccent</item>
    </style>
</resources>

答案 4 :(得分:0)

直接添加这个就可以解决问题了。

//this is the JSON file

[{
    "id" : "cnj01",
    "form_id" : "cnj_form",
    "title" : "Conejita dormilona",
    "name" : "conejitadormilona",
    "description" : "Conejita tejida con hilo fino rosa, sin accesorios.",
    "description_mid" : "Conejita tejida al crochet con hilo mediano color rosa. Se pueden incluir accesorios como chaleco o bufanda.",
    "description_long" : "Conejita tejida al crochet con hilo mediano color rosa. Rellenada con vellón siliconado. La altura es de 22 cm. El accesorio incluído es una vincha tejida con el mismo tipo y color de hilo. También se pueden incluir accesorios como chaleco o bufanda con colores a elección.",
    "price" : 850,
    "cant" : 1,
    "image" : "images/products/conejita.jpg",
    "altimg" : "conejita dormilona - mununuras.ar - juguetes de apego",
    "stock" : 4
},
{
    "id" : "zrt01",
    "form_id" : "zrt_form",
    "title" : "Zorrito cariñoso",
    "name" : "zorritocarinoso",
    "description" : "Zorrito tejido en hilo fino con ojos de seguridad.",
    "description_mid" : "Este simpático zorrito viene con un ocico plástico y ojitos de seguridad para los mas chiquitos.",
    "description_long" : "Este simpático zorrito viene con un ocico plástico y ojitos de seguridad para los mas chiquitos. Rellenada con vellón siliconado. La altura es de 14 cm. Tejido en hilo mediano de color negro, blanco y marron anaranjado.",
    "price" : 950,
    "cant" : 1,
    "image" : "images/products/zorrito.jpg",
    "altimg" : "zorrito cariñoso - mununuras.ar - juguetes de apego",
    "stock" : 3
},
{
    "id" : "mds01",
    "form_id" : "mds_form",
    "title" : "Llavero medusa",
    "name" : "llaveromedusa",
    "description" : "Llavero medusa, con anilla metálica pequeña.",
    "description_mid" : "Medusa tejida al crochet con hilo fino. Posee anilla de metal cosida. Viene en tres tamaños.",
    "description_long" : "Medusa tejida al crochet con hilo fino. Posee anilla de metal cosida. Viene en tres tamaños grande (7cm), mediano (5cm) y chico (3cm). Rellena con vellón siliconado. Ideal para regalar!",
    "price" : 550,
    "cant" : 1,
    "image" : "images/products/medusa.jpg",
    "altimg" : "Llavero medusa - mununuras.ar - juguetes de apego",
    "stock" : 10
},
{
    "id": "plt01",
    "form_id" : "plt_form",
    "title" : "Colgante de pollitos",
    "name" : "colgantepollito",
    "description" : "Colgante de tres pollitos con anillo transparente.",
    "description_mid" : "Cogante de tres pollitos con anillo transparente. Ideal para adornar tus cortinas.",
    "description_long" : "Colgante de tres pollitos tejidos al crochet, ideal para adornar tus cortinas. Viene en un único tamaño (45cm). Los pollitos están rellenos con vellón siliconado.",
    "price" : 750,
    "cant" : 1,
    "image" : "images/products/pollito.jpg",
    "altimg" : "Colgante de tres pollitos - mununuras.ar - juguetes de apego",
    "stock" : 5
}
]


// product constructor
class Product {
    constructor (id, form_id, title, name, description, description_mid, description_long, price, cant, image, altimg, stock) {
        this.id = id;
        this.form_id = form_id;
        this.title = title;
        this.name = name;
        this.description = description;
        this.description_mid = description_mid;
        this.description_long = description_long;
        this.price = parseFloat(price);
        this.cant = parseInt(cant);
        this.image = image;
        this.altimg = altimg;
        this.stock = parseInt(stock);
        this.subtotal = this.price * this.cant;
    }
}

// this is where I want to push every item of the JSON//
let shoppingCart = new Array;


const req = new XMLHttpRequest();
req.open('GET', 'scripts/products.json', true);
req.send();
req.onreadystatechange = function () {
    if (this.readyState == 4 && this.status == 200) {
        let data = JSON.parse(this.responseText);

        // this IS NOT WORKING
        data.forEach( (element) => {
            // this shows the correct data
            console.log(element);
            let product =  new Product (`${element.id}`, `${element.form_id}`, `${element.title}`, `${element.name}`, `${element.description}`, `${element.description_mid}`, `${element.description_long}`, `${element.price}`, `${element.cant}`, `${element.image}`, `${element.altimg}`, `${element.stock}`);
            shoppingCart.push(product);
//   these logs show me the correct data but when I do a console.log(shoppingCart) 
// out of this function, The only thig I get is "undefined".
            console.log(product);
            }
        )
        console.log(data);
        //the "for" below is writing my html without any problem.
        //That means the problem starts when I try to take the "data" content out of req.onreadystatechange = function ()
        // in order to push every item into shoppingCart
        for (item of data) {
            $("#show_products").append(`
            <article class="products__item">
            <div>
                <img src="${item.image}" alt="${item.altimg}">
            </div>
            <div class="products__item--description">
                <h3 tabindex=0>${item.title}</h3>
                <p tabindex=0>${item.description_mid}</p>
                <div class="products__item--description--buttons">
                    <a tabindex=0 href="#${item.id}_popup" class="know">know more</a>
                    <a tabindex=0 class="add" id="${item.form_id}">add to shopping cart</a>
                </div>
            </div>
        </article>
            <div id="${item.id}_popup" class="window__popup">
                <div class="container__popup">
                    <div class="popup"><a tabindex=0 href="" class="close__popoup">X</a>
                        <div><img src="${item.image}" alt="${item.altimg}"></div>
                            <div class="popup--description">
                                <div tabindex=0 class="title">${item.title}</div>
                                <p tabindex=0>${item.description_long}</p>
                            <div tabindex=0 class="price__popup">$950.-</div>
                            <a tabindex=0 class="add" id="zrt-btn2">add to shopping cart</a>
                        </div>
                    </div>
                </div>
            </div>
            `);
        }
    }
}
// here I can see al the items in the array
console.log(shoppingCart);

// but here, I get undefined
console.log(shoppingCart[0]);
console.log(shoppingCart[1]);
console.log(shoppingCart[2]);
// etc

...