【问题标题】:How to change font to default as defined in Xml?如何将字体更改为 Xml 中定义的默认字体?
【发布时间】:2013-10-21 14:54:40
【问题描述】:

我已经使用

更改了我的 Textviews 的字体
Typeface font = Typeface.createFromAsset(this.getAssets(),"fonts/Arial.ttf"); 

在我的 Xml 布局中,我有许多不同字体的文本视图,我想随时以编程方式保留它

尝试了以下

Typeface.DEFAULT 

Typeface font =null;

所有的文本视图都设置为相同的字体,而不是 Xml 中的字体

如何在不重启应用的情况下保留字体?

【问题讨论】:

    标签: java android xml fonts


    【解决方案1】:

    可能的解决方案是使用 TypeFace 类的静态实例。前段时间我在这个线程中提出了这个问题的解决方案:Access a typeface once from asset and use it as a reference。我希望你觉得它有用。

    【讨论】:

      【解决方案2】:

      步骤 1)创建一个类名作为 CustomTextView 并复制粘贴此代码,但确保自定义字体应为 Project Assets 文件夹。所以你可以替换字体名称。

      打包 YOUR_PACKAGE;

      public class CustomTextView extends TextView{
      
          public CustomButton(Context context) {
              super( context );
              setFont();
      
          }
      
          public CustomTextView (Context context, AttributeSet attrs) {
              super( context, attrs );
              setFont();
          }
      
          public CustomTextView (Context context, AttributeSet attrs, int defStyle) {
              super( context, attrs, defStyle );
              setFont();
          }
      
          private void setFont() {
              Typeface normal = Typeface.createFromAsset(getContext().getAssets(),"fonts/Arial.ttf");
              setTypeface( normal, Typeface.NORMAL );
      
          }
      }
      

      第 2 步)

      在你的布局中使用这个自定义的 TextView

      <LinearLayout
              android:id="@+id/signing_details"
                android:layout_width="fill_parent"
                android:layout_height="fill_parent"
                android:orientation="vertical"
              android:weightSum="100" >
      
      <YOUR_PACKAGE.CustomTextView
                      android:id="@+id/textview"
                      android:layout_width="wrap_content"
                      android:layout_height="wrap_content"
                       android:text="@string/app_name"
                       android:textSize="16sp" />
      </ LinearLayout>
      

      你也可以动态使用这个CustomTextView

       CustomTextView textView = new CustomTextView (this);
       textView.setText(res.getString(R.string.app_name));
       textView.setTextColor(Color.parseColor("#000000"));
       textView.setTextSize(16);
      

      希望对您有所帮助。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-02-22
        • 1970-01-01
        • 2018-01-17
        • 2016-04-10
        • 2011-06-23
        • 1970-01-01
        相关资源
        最近更新 更多