以编程方式为api少于23

时间:2017-04-12 18:23:43

标签: java android

我想使用setTextAppearance更改按钮的样式,但是,抛出"折旧" .how如何正确使用setTextAppearance?

styles.xml



<resources>

    <!-- Base application theme. -->
    <style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
        <!-- Customize your theme here. -->
        <item name="colorPrimary">@color/colorPrimary</item>
        <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
        <item name="colorAccent">@color/colorAccent</item>
    </style>

    <style name="button_custom" parent="Theme.AppCompat.Light">
        <item name="colorControlHighlight">#FFF59D</item>
        <item name="colorButtonNormal">#FFF59D</item>
    </style>

</resources>
&#13;
&#13;
&#13;

活动

公共类MainActivity扩展了AppCompatActivity {

Button btn;
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    btn = (Button) findViewById(R.id.button);
    context = this;

    btn.setTextAppearance(context,R.style.button_custom);

}

public void setTextAppearance(Context context, int resId) {
    if (Build.VERSION.SDK_INT < 23) {
        super.setTextAppearance(context, resId);
    }
    else { super.setTextAppearance(resId);
    }
}

}

1 个答案:

答案 0 :(得分:0)

您可以尝试使用AppCompatButton类型的按钮并使用

btn.setTextAppearance(resid)

它还可以帮助您避免Build.VERSION.SDK_INT分支

您可以按照此文档https://developer.android.com/reference/android/support/v7/widget/AppCompatButton.html#setTextAppearance(android.content.Context,int)

User AppCompatButton

<android.support.v7.widget.AppCompatButton
       android:id="@+id/some_button"
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"/>