2015-08-28 45 views
4

是否可以通過編程方式將Widget.AppCompat.Button主題應用於按鈕?以編程方式將主題應用到按鈕

Button button = new Button(context); 
button.setText("Button"); 

目前,我使用的是試圖實現像程序兼容性主題風格的自定義繪製資源,但我認爲這可能是更容易實現。

在佈局它實現這樣的:提前

<Button 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:theme="@style/ThemeBasedOnAppcompatButton"/> 

感謝。

回答

10

您應該使用ContextThemeWrapper,它會更改默認主題。剛剛得到一個背景下,你通常會,並用它象下面這樣:

new Button(new ContextThemeWrapper(context, R.style.my_theme)); 
+0

謝謝!我想我的方法來實現動態佈局是錯誤的。我會用listview適配器替換它。 –

0

如果您需要progamatically更換主題和您使用的是支持庫,你可以簡單地使用:

TextViewCompat.setTextAppearance(getContext(), R.style.AppTheme_TextStyle_ButtonDefault_Whatever); 
用於TextViews和Buttons的

。其餘的視圖有類似的類:-)

相關問題