2016-11-20 55 views
0

這是我的風格:風格並不完全工作程序

<style name="buttonQuestionStyle" parent="@style/Widget.AppCompat.Button.Colored"> 
    <item name="android:layout_width">match_parent</item> 
    <item name="android:layout_height">wrap_content</item> 
    <item name="android:textColor">@color/white</item> 
    <item name="android:textSize">16sp</item> 
    <item name="android:padding">25dp</item> 
    <item name="android:layout_margin">10dp</item> 
    <item name="android:background">@color/questionButton</item> 
</style> 

在這裏,我的代碼:

Button btn = new Button(getActivity()); 
btn.setText(ojb.getText()); 
if (Build.VERSION.SDK_INT < 23) { 
    btn.setTextAppearance(getActivity(), R.style.buttonQuestionStyle); 
} else { 
    btn.setTextAppearance(R.style.buttonQuestionStyle); 
} 

在應用程序中:

編程按鈕會出現這樣的: programmatically button

並通過它的工作佈局。出現這樣的: xml layout button

這是我在XML佈局代碼:

<Button 
    android:text="Question" 
    style="@style/buttonQuestionStyle" /> 

所以...我不知道爲什麼會發生,以及如何解決它。

回答

1

您還不能以編程方式設置視圖樣式,但您可能會發現這個thread有用。

+0

謝謝,它爲我工作 –

0

身邊,爲什麼你不能設置按鈕的風格編程的一些信息,如每個方法setTextAppearance的JavaDoc的

Sets the text appearance from the specified style resource. 
<p> 
Use a framework-defined {@code TextAppearance} style like 
{@link android.R.style#TextAppearance_Material_Body1 @android:style/TextAppearance.Material.Body1} 
or see {@link android.R.styleable#TextAppearance TextAppearance} for the 
set of attributes that can be used in a custom style. 
    @param resId the resource identifier of the style to apply 
@attr ref android.R.styleable#TextView_textAppearance 

所以只用文本外觀沒有其他風格的元素交易。

不過,如果你想在runtime programmatically應用一些風格,你需要

  1. 使每一位單獨更改例如設置background你需要調用setBackground,類似的還有其他案件。

  2. 充氣該view編程方式使用該特定的主題。

2

可以在構造函數傳遞一個ContextThemeWrapper的按鈕,並使用3個參數的構造函數Button(context, attributeset, defStyle)

ContextThemeWrapper wrapper = new ContextThemeWrapper(this,R.style.buttonQuestionStyle); 
Button btn = new Button(wrapper, null, 0); // note this constructor 
btn.setText("some text");