以编程方式创建一个视图后,添加样式 [英] Add Style after creating a View programmatically

查看:196
本文介绍了以编程方式创建一个视图后,添加样式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

标题说明了一切,希望。

The Title says it all, hopefully.

1)我创建一个视图以编程方式:

1) I create a View programmatically:

RelativeLayout rl = new RelativeLayout(this);

2)我想将它添加到现有的LinearLayout之后,我想样式添加到RelativeLayout的。是这样的:

2) I want to add it to an existing LinearLayout and after that i want to add a Style to the RelativeLayout. Something like:

LinearLayout ll = (LinearLayout) findViewById(R.id.MyLinearLayout);
RelativeLayout rl = new RelativeLayout(this);
ll.addView(rl);
//add Style to rl here

我无法找到一个方法来做到这一点!

I can't find a way to do that!

我知道有办法以编程方式添加样式。是这样的:

I know there are ways to add a Style programmatically. Something like:

RelativeLayout rl = new RelativeLayout(this, null, R.style.MyRelativeLayout);

但是,这会增加我的风格已经添加的RelativeLayout到的LinearLayout之前。
因此,RelativeLayout的不是印,因为他应该怎么知道的LinearLayout是他的父母之前,我把它添加到的LinearLayout。

But this will add the style before i've added the relativelayout to the linearlayout. Therefore the relativelayout isn't "printed" because how should he know that the linearlayout is his parent before i add it to the linearlayout.

有谁有办法如何这一观点已创建并添加到父后以编程方式添加样式到视图?

Does anybody has a way how to add a Style programmatically to a view after this view has been created and added to a parent?

希望你明白我的意思。

推荐答案

您不能构建一个视图后,应用样式。要做到这一点,正确的方法是使用在Android 5.0以上版本的4个参数的构造函数或创建引用你的风格主题的属性,并使用3-参数构造函数。

You can't apply a style after constructing a view. The correct way to do this is to use the 4-argument constructor on Android 5.0+ or to create a theme attribute that references your style and use the 3-argument constructor.

// Works on versions prior to Android 5.0
RelativeLayout rl = new RelativeLayout(this, null, R.attr.myRelativeLayoutStyle);

// Works on Android 5.0 and above
RelativeLayout r2 = new RelativeLayout(this, null, 0, R.style.MyRelativeLayout);

RES /价值/ attrs.xml:

res/values/attrs.xml:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <attr name="myRelativeLayoutStyle" format="reference" />
    ...

RES /价值/ styles.xml:

res/values/styles.xml:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <style name="MyRelativeLayout">
        ...
    </style>
    ...

RES /价值/的themes.xml:

res/values/themes.xml:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <style name="MyAppTheme" parent="...">
        <item name="myRelativeLayoutStyle">@style/MyRelativeLayout</item>
        ...

这篇关于以编程方式创建一个视图后,添加样式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆