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

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


当前回答

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

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

其他回答

我在我的复合ViewGroup中使用XML定义的视图,将它们添加到ViewGroup中。这样我就不能动态地更改样式,但是我可以进行一些样式自定义。我的组合:

public class CalendarView extends LinearLayout {

private GridView mCalendarGrid;
private LinearLayout mActiveCalendars;

private CalendarAdapter calendarAdapter;

public CalendarView(Context context) {
    super(context);

}

public CalendarView(Context context, AttributeSet attrs) {
    super(context, attrs);

}

@Override
protected void onFinishInflate() {
    super.onFinishInflate();
    init();
}

private void init() {
    mCalendarGrid = (GridView) findViewById(R.id.calendarContents);
    mCalendarGrid.setNumColumns(CalendarAdapter.NUM_COLS);

    calendarAdapter = new CalendarAdapter(getContext());
    mCalendarGrid.setAdapter(calendarAdapter);
    mActiveCalendars = (LinearLayout) findViewById(R.id.calendarFooter);
}

}

在XML视图中,我可以指定样式:

<com.mfitbs.android.calendar.CalendarView
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/calendar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:orientation="vertical"
>

<GridView
    android:id="@+id/calendarContents"
    android:layout_width="match_parent"
    android:layout_height="wrap_content" />

<LinearLayout
    android:id="@+id/calendarFooter"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    />

int buttonStyle = R.style.your_button_style;
Button button = new Button(new ContextThemeWrapper(context, buttonStyle), null, buttonStyle);

只有这个答案对我有用。参见https://stackoverflow.com/a/24438579/5093308

更新:在回答这个问题的时候(2012年中期,API级别14-15),以编程方式设置视图还不是一个选项(即使有一些重要的变通方法),而在最近的API发布之后,这已经成为可能。详见@Blundell的回答。

旧的回答:

您还不能通过编程方式设置视图的样式,但是您可能会发现这个线程很有用。

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

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

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

https://github.com/airbnb/paris

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

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

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