我想通過自定義字體更改android片段中多個TextView的默認字體。做到這一點的代碼在thefragment的onCreateView如下所示:如何將自定義字體應用於片段中的多個TextView?
@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但試圖改變字體多個TextViews作爲代碼工作代碼上面,我得到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。提前致謝 !!
確保您提到的文字視圖出現在您的佈局中。 – Neji
分享你的'fragment_interest.xml' .. !! –
確保在佈局中使用textview1和textview2的textview1和textview2 fragment_interest.xml –