如何将自定义字体应用于片段中的多个TextView?

时间:2016-06-14 07:28:11

标签: android fragment typeface

我试图通过自定义字体更改android片段中多个TextView的默认字体。完成此操作的代码位于thefragment的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;

}

如果我只更改单个TextView的字体,但尝试更改多个TextView的字体,如上面的代码,代码有效,我收到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。在此先感谢!!

4 个答案:

答案 0 :(得分:0)

添加此行

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

这里,我使用“Roboto-Light”这种字体样式

答案 1 :(得分:0)

您可以使用Calligraphy来执行此操作。 (为什么在已经完成任务时重新发明轮子)

包含依赖

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

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

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

@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"/>

答案 2 :(得分:0)

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

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);
        }
    }

}

答案 3 :(得分:0)

尝试查找TextView中的所有View并更改每种for( int i = 0; i < mainView.getChildCount(); i++ ){ if( mainView.getChildAt( i ) instanceof TextView ) mainView.getChildAt( i ).setTypeface(GloabalTypeface._globalTypeface(this, "Roboto-Light")); } 的字体:

oldSize