【问题标题】:Android : XML buttons and programmatically created buttons have slightly different font weight (with same attributes)Android:XML 按钮和以编程方式创建的按钮的字体粗细略有不同(具有相同的属性)
【发布时间】:2017-12-05 00:30:01
【问题描述】:

我有一个在 ScrollView 中有多个按钮的应用,我在 Activity 启动后以编程方式添加更多按钮(自定义用户按钮)。

所有按钮都具有相同的样式和属性,但在屏幕上以编程方式创建的按钮的文本略显粗体。

我在布局检查器中检查了它们,它们都具有相同的属性值,例如 getTextSize (20)、getTypefaceStyle (NORMAL)、高度、宽度、样式......

什么会导致这些属性的相同值的粗体不同?

一个 XML 按钮的示例:

            <Button
            android:id="@+id/button_autre"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:background="@drawable/background_selector2o"
            android:text="Bonbons"
            android:textAppearance="@style/TextAppearance.AppCompat"
            android:textStyle="normal"
            android:textAllCaps="false"
            android:textColor="#ffffff"
            android:textSize="20sp"
            android:layout_marginTop="20dp"
            />

一个创建按钮的示例:

        LinearLayout layout = (LinearLayout) view.findViewById(R.id.buttons_container);

        LinearLayout.LayoutParams layoutparams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
        layoutparams.setMargins(0, px, 0, 0); // px calculated to be 20dp

        ContextThemeWrapper ndfContext = new ContextThemeWrapper(getActivity(), R.style.button_style_xml);
        Button addbutton = new Button(ndfContext);
        addbutton.setLayoutParams(layoutparams);
        addbutton.setText("Bonbons");
        addbutton.setBackgroundResource(R.drawable.background_selector2o);
        layout.addView(addbutton);

button_style_xml 的内容:

<resources>
    <style name="ndftype_style" parent="AppTheme.NoActionBar">
        <item name="android:background">@drawable/background_selector2o</item>
        <item name="android:textAppearance">@style/TextAppearance.AppCompat</item>
        <item name="android:textColor">#ffffff</item>
        <item name="android:textSize">20sp</item>
        <item name="android:layout_marginTop">20dp</item>
        <item name="android:textAllCaps">false</item>
        <item name="android:textStyle">normal</item>
    </style>
</resources>

结果:

【问题讨论】:

    标签: java android xml layout fonts


    【解决方案1】:

    通常情况下,我在写问题时有个想法,感谢金丝雀效应。

    尽管所有按钮都具有相同的样式并且在任何地方都没有为其分配字体,但似乎 Android 为这两种类型分配了不同的默认字体。我不知道为什么会这样。

    添加

    <item name="android:fontFamily">sans-serif</item>
    

    在我以编程方式创建的按钮上解决了这个问题。 为了安全起见,您可能也希望将其添加到 XML 按钮中。

    如果您的目标 API 级别

    button.setTypeface(Typeface.DEFAULT);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-01-30
      • 1970-01-01
      • 1970-01-01
      • 2018-03-03
      • 2021-07-05
      相关资源
      最近更新 更多