【问题标题】:set custom font for text in PreferenceScreen在 PreferenceScreen 中为文本设置自定义字体
【发布时间】:2012-11-02 10:27:03
【问题描述】:

我的 PreferenceActivity 看起来像:

import android.os.Build;
import android.os.Bundle;
import android.preference.PreferenceActivity;
import android.preference.PreferenceFragment;
import android.widget.TextView;

public class Settings extends PreferenceActivity {

    @SuppressWarnings("deprecation")
    @Override
    protected void onCreate(Bundle savedInstanceState) 
    {
            super.onCreate(savedInstanceState);

            //setContentView(R.layout.about);

            Typeface timesFont = Typeface.createFromAsset(getAssets(), "fonts/times.ttf");

            TextView about_txt = (TextView) findViewById(R.id.about_txt);        
            about_txt.setTypeface(timesFont);
            about_txt.setText(R.string.about_txt);


            if (Build.VERSION.SDK_INT<Build.VERSION_CODES.HONEYCOMB)
            {
                addPreferencesFromResource(R.xml.preferences);
            } else {
                // Display the fragment as the main content.
                getFragmentManager().beginTransaction().replace(android.R.id.content,
                        new PrefsFragment()).commit();
            }
    }

    public static class PrefsFragment extends PreferenceFragment 
    {
            @Override
            public void onCreate(Bundle savedInstanceState) {
                super.onCreate(savedInstanceState);

                // Load the preferences from an XML resource
                addPreferencesFromResource(R.xml.preferences);
            }
        }
}

还有preference.xml

<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">

        <ListPreference
            android:dialogTitle="@string/size_dialog"
            android:entries="@array/size_list"
            android:entryValues="@array/entry_size"
            android:key="size_list"
            android:summary="@string/size_summary"
            android:title="@string/pref4title"
            />

    </PreferenceCategory>

    <PreferenceCategory
        android:title="@string/pref_about"
        android:layout="@layout/about"
        >

    </PreferenceCategory>

</PreferenceScreen>

@layout/about (about.xml):

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
         xmlns:tools="http://schemas.android.com/tools"
         android:layout_width="match_parent"
         android:layout_height="match_parent"> 

          <TextView
            android:id="@+id/about_txt"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="some text here"   
            />

</LinearLayout>

我有特定的语言,所以对于 about.xml 中的文本我应该使用特定的字体。我经常为 TextView 使用:

 Typeface timesFont = Typeface.createFromAsset(getAssets(), "fonts/times.ttf");

 TextView about_txt = (TextView) findViewById(R.id.about_txt);        
 about_txt.setTypeface(timesFont);
 about_txt.setText(R.string.about_txt);

但是我应该使用什么来访问 about.xml 中添加到首选项屏幕的文本?

提前致谢!

【问题讨论】:

    标签: android android-preferences preferenceactivity


    【解决方案1】:

    也许更容易编写自己的首选项并将其添加到 xml
    只需通过 Spannable 将 自定义字体设置为设置字段
    (看起来很长,但完成得很快 :))

    完整解决方案:

    private void convertPreferenceToUseCustomFont(Preference somePreference) {
        CustomTypefaceSpan customTypefaceSpan = new CustomTypefaceSpan("", net.mikekober.myMory.utils.Utils.getUsedTypeFace(getActivity()));
    
        SpannableStringBuilder ss;
        if (somePreference.getTitle() != null) {
            ss = new SpannableStringBuilder(somePreference.getTitle().toString());
            ss.setSpan(customTypefaceSpan, 0, ss.length(),Spanned.SPAN_EXCLUSIVE_INCLUSIVE);
            somePreference.setTitle(ss);
        }
    
        if (somePreference.getSummary() != null) {
            ss = new SpannableStringBuilder(somePreference.getSummary().toString());
            ss.setSpan(customTypefaceSpan, 0, ss.length(),Spanned.SPAN_EXCLUSIVE_INCLUSIVE);
            somePreference.setSummary(ss);
        }
    }
    

    为每一个偏好调用它,你就完成了:)

    玩得开心,祝你好运

    顺便说一句:在更改文本时,再次调用它!
    btw2:检查、查看、应用、改进;)来自:https://stackoverflow.com/a/10741161/371749

    btw3,差点忘了:

    static private class CustomTypefaceSpan extends TypefaceSpan {
    
        private final Typeface newType;
    
        public CustomTypefaceSpan(String family, Typeface type) {
            super(family);
            newType = type;
        }
    
        @Override
        public void updateDrawState(TextPaint ds) {
            applyCustomTypeFace(ds, newType);
        }
    
        @Override
        public void updateMeasureState(TextPaint paint) {
            applyCustomTypeFace(paint, newType);
        }
    
        private static void applyCustomTypeFace(Paint paint, Typeface tf) {
            int oldStyle;
            Typeface old = paint.getTypeface();
            if (old == null) {
                oldStyle = 0;
            } else {
                oldStyle = old.getStyle();
            }
    
            int fake = oldStyle & ~tf.getStyle();
            if ((fake & Typeface.BOLD) != 0) {
                paint.setFakeBoldText(true);
            }
    
            if ((fake & Typeface.ITALIC) != 0) {
                paint.setTextSkewX(-0.25f);
            }
    
            paint.setTypeface(tf);
        }
    }
    

    【讨论】:

    • 感谢您提供简单的解决方案。自定义字体应用于除summaryListPreference 之外的所有文本。你知道如何更改summary 字体吗?
    • @Nolesh 的解决方案也适用于汇总字段,而且是更好的解决方案。
    【解决方案2】:

    PreferenceScreen 中的所有TextViews 更改字体的最简单方法是:

    public class WallpaperSettings extends PreferenceActivity {
    
      private View tryInflate(String name, Context context, AttributeSet attrs) {
        LayoutInflater li = LayoutInflater.from(context);
        View v = null;
        try {
            v = li.createView(name, null, attrs); 
        } catch (Exception e) {
            try {
                v = li.createView("android.widget." + name, null, attrs);
            } catch (Exception e1) {
            }
        }
        return v;
      }
    
      protected void onCreate(Bundle savedInstanceState) {
        //CHANGE TYPEFACE FOR ALL TEXTVIEWS
        final Typeface font = Typeface.createFromAsset(getAssets(), "fonts/cabal.ttf");     
        getLayoutInflater().setFactory(new Factory() {
            @Override
            public View onCreateView(String name, Context context,
                    AttributeSet attrs) {
                View v = tryInflate(name, context, attrs);
                if (v instanceof TextView) {                    
                    ((TextView) v).setTypeface(font);
                }
                return v;
            }
        });
    
        super.onCreate(savedInstanceState);
        addPreferencesFromResource(R.xml.prefs);
      }
    }
    

    就是这样!

    【讨论】:

      【解决方案3】:
      public class CustomPreference extends Preference 
          implements PreferenceStyle {
      
          private int style;
      
          public CustomPreference(Context context, AttributeSet attrs, int defStyle) {
              super(context, attrs, defStyle);
      
          }
      
          public CustomPreference(Context context, AttributeSet attrs) {
              super(context, attrs);
          }
      
          public CustomPreference(Context context) {
              super(context);
          }
      
          @Override
          protected void onBindView(View view) {
              super.onBindView(view);
              switch (style) {
              case STYLE_ALARMED:
                  setStyleAlarmed(view);
                  break;
              case STYLE_NORMAL:
                  setStyleNormal(view);
                  break;
              case STYLE_WARNING:
                  setStyleWarning(view);
                  break;
              case STYLE_SUMMARY_ALARM:
                  setStyleSummaryAlarm(view);
                  break;
              case STYLE_SUMMARY_WARNING:
                  setStyleSummaryWarning(view);
                  break;
              case STYLE_DISABLED:
                  setStyleDisabled(view);
                  break;
              default:
                  break;
              }
      
          }
      
      private void setStyleWarning(View view) {
          TextView titleView = (TextView) view.findViewById(android.R.id.title);
          titleView.setTextColor(Color.YELLOW);
                  // add your FONT here
      }
      
      private void setStyleAlarmed(View view) {
          int alarmREDColor = view.getContext().getResources().getColor(R.color.alarmed_red);
          TextView titleView = (TextView) view.findViewById(android.R.id.title);
          titleView.setTextColor(alarmREDColor);
      }
      
      public void setStyle(int style) {
              switch (style) {
              case STYLE_ALARMED:
                  this.style = STYLE_ALARMED;
                  break;
              case STYLE_NORMAL:
                  this.style = STYLE_NORMAL;
                  break;
              default:
                  this.style = STYLE_NORMAL;
              }
          }
      
      public interface PreferenceStyle {
      
          public static final int STYLE_DISABLED = 0;
          public static final int STYLE_NORMAL = 10;
          public static final int STYLE_ALARMED = 20;
          public static final int STYLE_WARNING = 30;
      
          public static final int STYLE_SUMMARY_ALARM = 40;
          public static final int STYLE_SUMMARY_WARNING = 50;
      
          public void setStyle(int style);
          public Context getContext();
          public void setSummary(CharSequence summary);
      
      }
      

      public class YourActivity extends PreferenceActivity {
      
          private CustomPreference pref1;
          private CustomPreference pref2;
          private CustomPreference pref3;
      
      
          @Override
          public void onCreate(Bundle savedInstanceState) {
              super.onCreate(savedInstanceState);         
              addPreferencesFromResource(R.xml.prefence_xml);
              pref1 = findPreference();
                          pref1.setOnPreferenceClickListener(this);
                          pref1.setStyle(PreferenceStyle.STYLE_NORMAL);
                     }
              }
      

      <PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android" >
      
      
          <PreferenceCategory 
              android:title="category1">
      
              <com.project.main.preference.CustomPreference 
                  android:key="key"
                  android:title="title"
                  />  
      
              <com.project.main.preference.CustomPreference 
                  android:key="key"
                  android:title="title"/>
      
          </PreferenceCategory>
      
      </PreferenceScreen>
      

      【讨论】:

      • 感谢您的快速回答,但是当我“扩展 Preference”而不是“PreferenceActivity”时,就无法使用 addPreferencesFromResource。还是我做错了什么?
      • 将自定义首选项放入您的 PreferenceActivity
      • 我将“new CustomPreference(this)”放在“super.onCreate(savedInstanceState)”之后的 PreferenceActivity 中,但没有任何改变。我还添加了更改 onBindView(View view) {super.onBindView(view);Typeface timesFont =Typeface.createFromAsset(this.context.getAssets(), "fonts/times.ttf"); TextView about_txt = (TextView) view.findViewById(android.R.id.title); about_txt.setTypeface(timesFont);} 但没有效果
      • CustomPreference 是 ui 元素 - 你应该调用它 (CustomPreference) findPreference();
      • 能否请您用正确的方式更新您的帖子以调用 CustomPreference 并更改字体...因为我尝试的一切都不起作用
      【解决方案4】:

      通过在 android O 中添加字体支持,我们现在可以为应用主题设置 font-family,这也会自动反映在 PreferenceFragment 中。 (注意:我使用的是PreferenceFragmentCompat)。首先在资源中添加font-family,如下所示:

      <font-family xmlns:android="http://schemas.android.com/apk/res/android"
      xmlns:app="http://schemas.android.com/apk/res-auto">
      <font
          android:fontStyle="normal"
          android:fontWeight="400"
          android:font="@font/nunito"
      
          app:fontStyle="normal"
          app:fontWeight="400"
          app:font="@font/nunito"/>
      
      <font
          android:fontStyle="italic"
          android:fontWeight="400"
          android:font="@font/nunito_italic"
      
          app:fontStyle="italic"
          app:fontWeight="400"
          app:font="@font/nunito_italic" />
      

      注意:您现在需要 appandroid 命名空间声明 Link

      然后为 TextView 提及此 font-family 的文本视图添加 style

      <style name="NunitoTextViewStyle" parent="android:Widget.TextView">
          <item name="android:fontFamily">@font/nunito_regular_font_family</item>
      </style>
      

      最后,只需在您的AppTheme 中引用上述style,如下所示:

      <style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
          <!-- Customize your theme here. -->
          ........
          <item name="android:textViewStyle">@style/NunitoTextViewStyle</item>
      </style>
      

      完成。这也会在您的PreferenceFragmentCompat 中显示自定义字体。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-01-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-11-22
        相关资源
        最近更新 更多