首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >Android:以编程方式设置视图样式

Android:以编程方式设置视图样式
EN

Stack Overflow用户
提问于 2012-07-30 22:47:51
回答 16查看 310.9K关注 0票数 259

下面是XML:

代码语言:javascript
复制
<RelativeLayout 
    xmlns:android="http://schemas.android.com/apk/res/android"
    style="@style/LightStyle"
    android:layout_width="fill_parent"
    android:layout_height="55dip"
    android:clickable="true"
    android:orientation="horizontal" >

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="horizontal" />

</RelativeLayout>

如何以编程方式设置style属性?

EN

回答 16

Stack Overflow用户

回答已采纳

发布于 2014-01-10 19:38:11

从技术上讲,您可以通过编程方式应用样式,但无论如何都可以使用自定义视图:

代码语言:javascript
复制
private MyRelativeLayout extends RelativeLayout {
  public MyRelativeLayout(Context context) {
     super(context, null, R.style.LightStyle);
  }
}

单参数构造函数是以编程方式实例化视图时使用的构造函数。

因此,将此构造函数链接到接受style参数的超级函数。

代码语言:javascript
复制
RelativeLayout someLayout = new MyRelativeLayout(new ContextThemeWrapper(this,R.style.RadioButton));

或者正如@Dori简单地指出的那样:

代码语言:javascript
复制
RelativeLayout someLayout = new RelativeLayout(new ContextThemeWrapper(activity,R.style.LightStyle));

现在在Kotlin:

代码语言:javascript
复制
class MyRelativeLayout @JvmOverloads constructor(
    context: Context, 
    attributeSet: AttributeSet? = null, 
    defStyleAttr: Int = R.style.LightStyle,
) : RelativeLayout(context, attributeSet, defStyleAttr)

代码语言:javascript
复制
 val rl = RelativeLayout(ContextThemeWrapper(activity, R.style.LightStyle))
票数 248
EN

Stack Overflow用户

发布于 2015-02-20 01:35:08

对我起作用的是:

代码语言:javascript
复制
Button b = new Button(new ContextThemeWrapper(this, R.style.ButtonText), null, 0);

使用ContextThemeWrapper的

  • 使用3参数构造函数(没有此函数将不起作用)
票数 142
EN

Stack Overflow用户

发布于 2012-07-30 22:54:32

after :在回答这个问题时( 2012年中,级别14-15),以编程方式设置视图不是一个选项(即使有一些很重要的变通方法),而在最近的发布之后,这已经成为可能。有关详细信息,请参阅@Blundell的答案。

的老答案:

您还不能以编程方式设置视图的样式,但您可能会发现this thread很有用。

票数 93
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/11723881

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档