如何将自定义字体应用于片段中的多个文本视图



我正在尝试通过自定义字体更改 android 片段中多个文本视图的默认字体。完成此操作的代码位于片段的 onCreateView 中,如下所示:

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    View v = inflater.inflate(R.layout.fragment_interest, container, false);
    TextView txt1 = (TextView)v.findViewById(R.id.textView1);
    TextView txt2 = (TextView)v.findViewById(R.id.textView2);
    Typeface font = Typeface.createFromAsset(getActivity().getAssets(), "fonts/HoneyScript-SemiBold.ttf");
    txt1.setTypeface(font);
    txt2.setTypeface(font);
    return v;

}

如果我只更改单个文本视图的字体,

但尝试更改多个文本视图的字体,如上面的代码所示,则代码有效,我收到 NullPointerException 错误:

java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setTypeface(android.graphics.Typeface)' on a null object reference
                                                                                     at layout.InterestFragment.onCreateView(InterestFragment.java:81)
                                                                                     at android.support.v4.app.Fragment.performCreateView(Fragment.java:1962)
                                                                                     at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1067)
                                                                                     at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1248)
                                                                                     at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:738)
                                                                                     at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1613)
                                                                                     at android.support.v4.app.FragmentController.execPendingActions(FragmentController.java:330)
                                                                                     at android.support.v4.app.FragmentActivity.onStart(FragmentActivity.java:547)
                                                                                     at com.android.niraj.financialcalculator.MainActivity.onStart(MainActivity.java:221)
                                                                                     at android.app.Instrumentation.callActivityOnStart(Instrumentation.java:1237)
                                                                                     at android.app.Activity.performStart(Activity.java:6253)
                                                                                     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2379)
                                                                                     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476) 
                                                                                     at android.app.ActivityThread.-wrap11(ActivityThread.java) 
                                                                                     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344) 
                                                                                     at android.os.Handler.dispatchMessage(Handler.java:102) 
                                                                                     at android.os.Looper.loop(Looper.java:148) 
                                                                                     at android.app.ActivityThread.main(ActivityThread.java:5417) 
                                                                                     at java.lang.reflect.Method.invoke(Native Method) 
                                                                                     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726) 
                                                                                     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616) 

我是Java和Android编程的新手。请帮助我找到使用自定义字体更改片段中所有文本视图的解决方案。提前感谢!!

添加此行

textview.setTypeface(GloabalTypeface._globalTypeface(this, "Roboto-Light"));

在这里,我使用的是"机器人光"这种字体样式

您可以使用书法来做到这一点。(当某件事已经完成时,为什么要重新发明轮子)

包括依赖项

dependencies {
    compile 'uk.co.chrisjenx:calligraphy:2.2.0'
}

将自定义字体添加到资产/所有字体定义都与此路径相关。

使用 CalligraphyConfig 在 #onCreate() 方法的应用程序类中定义默认字体。

@Override
public void onCreate() {
    super.onCreate();
    CalligraphyConfig.initDefault(new CalligraphyConfig.Builder()
                            .setDefaultFontPath("fonts/Roboto-RobotoRegular.ttf")
                            .setFontAttrId(R.attr.fontPath)
                            .build()
            );
    //....
}

包装活动上下文:

@Override
protected void attachBaseContext(Context newBase) {
    super.attachBaseContext(CalligraphyContextWrapper.wrap(newBase));
}

你很好!

<TextView
    android:text="@string/hello_world"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    fontPath="fonts/Roboto-Bold.ttf"/>

只需通过将父视图作为参数传递来调用这些方法。

private void overrideFonts(final Context context, final View v) {
    try {
        if (v instanceof ViewGroup) {
            ViewGroup vg = (ViewGroup) v;
            for (int i = 0; i < vg.getChildCount(); i++) {
                View child = vg.getChildAt(i);
                overrideFonts(context, child);
         }
        } else if (v instanceof TextView ) {
            ((TextView) v).setTypeface(Typeface.createFromAsset(context.getAssets(), "font.ttf"));
        }
    } catch (Exception e) {
 }
 }

应用字体以不在运行时查看自身(最佳性能)

public class MyTextView extends TextView {
    public MyTextView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        init();
    }
    public MyTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }
    public MyTextView(Context context) {
        super(context);
        init();
    }
    private void init() {
        if (!isInEditMode()) {
            Typeface tf = Typeface.createFromAsset(getContext().getAssets(), "font.ttf");
            setTypeface(tf);
        }
    }
}

尝试查找View中的所有TextView并更改每个的字体:

for( int i = 0; i < mainView.getChildCount(); i++ ){
  if( mainView.getChildAt( i ) instanceof TextView )
    mainView.getChildAt( i ).setTypeface(GloabalTypeface._globalTypeface(this, "Roboto-Light"));
}

最新更新