NullPointerException初始化片段中的视图 [英] NullPointerException Initialize View in Fragment
本文介绍了NullPointerException初始化片段中的视图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我使用Fragment将我的内容保存在TabLayout中.在里面,我有按钮.当我尝试在Fragment类中实例化时,出现以下错误:
i use Fragment to hold my content in TabLayout. Inside it, i have Button. When i try to instantiate in Fragment class i get this following error :
com.example.fanjavaid.tablayout E/AndroidRuntime: FATAL EXCEPTION: main
java.lang.NullPointerException
at com.example.fanjavaid.tablayout.fragment.AccountFragment.onCreateView(AccountFragment.java:27)
at android.support.v4.app.Fragment.performCreateView(Fragment.java:2080)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1108)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1290)
at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:801)
at android.support.v4.app.FragmentManagerImpl.execSingleAction(FragmentManager.java:1638)
at android.support.v4.app.BackStackRecord.commitNowAllowingStateLoss(BackStackRecord.java:679)
at android.support.v4.app.FragmentStatePagerAdapter.finishUpdate(FragmentStatePagerAdapter.java:166)
at android.support.v4.view.ViewPager.populate(ViewPager.java:1240)
at android.support.v4.view.ViewPager.populate(ViewPager.java:1088)
at android.support.v4.view.ViewPager.onMeasure(ViewPager.java:1614)
这是我在 onCreateView(...)
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
RelativeLayout mFragmentAccount = (RelativeLayout) getActivity().findViewById(R.id.fragment_account);
mBtnAddPerson = (Button) mFragmentAccount.findViewById(R.id.add_person);
Typeface font = Typeface.createFromAsset(mFragmentAccount.getContext().getAssets(), "/fonts/Rubik-Regular.ttf");
mBtnAddPerson.setTypeface(font);
return inflater.inflate(R.layout.fragment_account, mFragmentAccount,true);
}
这是我的Fragment XML布局:
And here is my Fragment XML layout :
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/fragment_account"
android:padding="@dimen/activity_horizontal_margin"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true"
android:text="Hello Android!"/>
<Button
android:id="@+id/add_person"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:gravity="center"
android:text="Add People"/>
</RelativeLayout>
我想念什么?
谢谢
推荐答案
您正在尝试从活动"中获取视图.您必须给片段充气.
You are trying to get your View from your Activity. You have to inflate your fragment.
View rootView = inflater.inflate(R.id.fragment_account, container, false);
这篇关于NullPointerException初始化片段中的视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文