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

其他回答

对于一个新的按钮/TextView:

Button mMyButton = new Button(new ContextThemeWrapper(this, R.style.button_disabled), null, 0);

对于已存在的实例:

mMyButton.setTextAppearance(this, R.style.button_enabled);

对于图像或布局:

Image mMyImage = new ImageView(new ContextThemeWrapper(context, R.style.article_image), null, 0);

你可以通过以下方式将样式应用到你的活动:

super.setTheme( R.style.MyAppTheme );

或Android默认设置:

super.setTheme( android.R.style.Theme );

在setContentView()之前。

我在我的复合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"
    />

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

对我有用的是:

Button b = new Button(new ContextThemeWrapper(this, R.style.ButtonText), null, 0);

使用ContextThemeWrapper

AND

使用3个参数的构造函数(没有这个就不行)