这是XML:

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

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


当前回答

如果您想继续使用XML(公认的答案不允许您这样做)并在创建视图后设置样式,那么您可以使用Paris库,它支持所有可用属性的一个子集。

因为你正在从XML扩展视图,你需要在布局中指定一个id:

<RelativeLayout 
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/my_styleable_relative_layout"
    style="@style/LightStyle"
    ...

然后,当你需要以编程方式改变样式时,在布局被膨胀后:

// Any way to get the view instance will do
RelativeLayout myView = findViewById(R.id.my_styleable_relative_layout);

// This will apply all the supported attribute values of the style
Paris.style(myView).apply(R.style.LightStyle);

更多信息:支持的视图类型和属性列表(包括背景、填充、边距等,并且可以很容易地扩展)和附加文档的安装说明。

声明:我是该库的原始作者。

其他回答

您可以创建包含所需样式的布局的xml,然后更改视图的背景资源,如下所示。

如果您想继续使用XML(公认的答案不允许您这样做)并在创建视图后设置样式,那么您可以使用Paris库,它支持所有可用属性的一个子集。

因为你正在从XML扩展视图,你需要在布局中指定一个id:

<RelativeLayout 
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/my_styleable_relative_layout"
    style="@style/LightStyle"
    ...

然后,当你需要以编程方式改变样式时,在布局被膨胀后:

// Any way to get the view instance will do
RelativeLayout myView = findViewById(R.id.my_styleable_relative_layout);

// This will apply all the supported attribute values of the style
Paris.style(myView).apply(R.style.LightStyle);

更多信息:支持的视图类型和属性列表(包括背景、填充、边距等,并且可以很容易地扩展)和附加文档的安装说明。

声明:我是该库的原始作者。

简单的方法是通过构造函数

RadioButton radioButton = new RadioButton(this,null,R.style.radiobutton_material_quiz);

如果在自己的自定义视图中: val editText = TextInputEditText(context, attrs, defStyleAttr)

我不建议使用ContextThemeWrapper,因为它这样做:

指定的主题将应用于 基本上下文的主题。

什么会在应用程序中产生不必要的结果。相反,我建议Airbnb的工程师们建造一个名为“paris”的图书馆:

https://github.com/airbnb/paris

以编程方式定义并应用样式到Android视图。

但在使用了一段时间后,我发现它实际上是相当有限的,我停止使用它,因为它不支持很多属性,我需要开箱即用,所以一个人必须检查并决定一如既往。