Android:以编程方式将样式设置为自定义按钮

时间:2017-05-09 14:12:06

标签: android textview android-spinner android-button

我有一个扩展Button的自定义视图。而我只想将belove风格设置为此视图。

    <style name="MultipleButtonStyle" parent="android:Widget.Material.Light.Spinner.Underlined">
        <item name="android:textColor">@android:color/black</item>
        <item name="android:textAppearance">?android:attr/textAppearanceMedium</item>
    </style>

为了能够以编程方式设置样式,我尝试了一些方法。但他们不适合我。

第一种方式,正在使用自定义按钮的构造函数中的样式,如下所示:

public class SpinnerButton extends AppCompatButton{

public SpinnerButton (Context context) {
        super(context, null, R.style.MultipleButtonStyle);

    }
}

第二种方式是使用setTextAppearance方法。它也不适用于我。

if (Build.VERSION.SDK_INT < 23) {
        super.setTextAppearance(getContext(), R.style.MultipleButtonStyle );
    } else {
        super.setTextAppearance(R.style.MultipleButtonStyle);
    }

1 个答案:

答案 0 :(得分:4)

你的构造函数看起来很好,你是否还要覆盖其他构造函数(例如,使用AttributeSet,这是从XML进行膨胀时调用的)?检查THIS关于View s构造函数和某些样式的问题

第二种方式是不合适的,因为你的风格的parent是整个Spinner.Underlined的风格,不仅仅是TextAppearance。在这种情况下,您应该扩展@android:style/TextAppearance.Medium(或其他)。如果您选择这种方式,那么请记住API23中已弃用的setTextAppearance方法,并且您可以使用一些帮助程序而不检查操作系统版本:

TextViewCompat.setTextAppearance(textView, android.R.style.TextAppearance_Medium);
相关问题