Android 以编程方式应用于按钮时,样式不能完全工作

Android 以编程方式应用于按钮时,样式不能完全工作,android,android-studio,android-fragments,Android,Android Studio,Android Fragments,以下是我的风格: <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> <ite

以下是我的风格:

<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>

匹配父项
包装内容
@颜色/白色
16便士
25dp
10dp
@颜色/问题按钮
这是我的代码:

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);
}
Button btn=新按钮(getActivity());
setText(ojb.getText());
如果(Build.VERSION.SDK_INT<23){
btn.setTextAppearance(getActivity(),R.style.buttonQuestionStyle);
}否则{
btn.setTextAppearance(R.style.buttonQuestionStyle);
}
在应用程序中:

以编程方式显示的按钮如下所示:

通过布局,它成功了。如下所示:

以下是我在XML布局中的代码:

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


所以。。。我不知道为什么会发生这种情况,以及如何修复它。

根据JavaDoc的方法
settextearance

设置指定样式资源中的文本外观。

使用框架定义的{@code TextAppearance}样式,如
{@link android.R.style#TextAppearance_Material_Body1@android:style/TextAppearance.Material.Body1}
或者参见{@link android.R.styleable#textpearance textpearance}获取
可在自定义样式中使用的属性集。
@param resId要应用的样式的资源标识符
@attr ref android.R.styleable#TextView_textAppearance
因此,它只处理文本外观,而不处理其他样式元素

但是,如果您想在
运行时以编程方式应用某种样式,则需要

  • 分别进行每项更改,例如设置
    背景
    ,您需要调用
    setBackground
    ,对于其他情况,也是如此

  • 使用该特定主题以编程方式对
    视图进行膨胀


  • 您可以在按钮的构造函数中传递一个
    ContextThemeWrapper
    ,并使用
    按钮的3个参数构造函数(context、attributeset、defStyle)


    您还不能以编程方式设置视图的样式,但您可能会发现这很有用。谢谢,它对我很有用
    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
    
    ContextThemeWrapper wrapper = new ContextThemeWrapper(this,R.style.buttonQuestionStyle);
    Button btn = new Button(wrapper, null, 0); // note this constructor
    btn.setText("some text");