在getActionBar()上获取nullpointerexception

时间:2017-05-17 06:08:45

标签: android android-fragments fragment android-tabbed-activity

我正在为片段中的操作栏添加标签。但是当我尝试启动该片段时,我的应用程序在抛出空指针异常后崩溃了

这是错误

Log

Home.java文件是这样的:

public class Home extends Fragment implements ActionBar.TabListener {

private ViewPager viewPager;
private TabPagerAdapter tabPagerAdapter;
private ActionBar actionBar;
private FragmentActivity fragmentActivity;

private String[] tabs ;

public Home() {
    // Required empty public constructor
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    View rootView = inflater.inflate(R.layout.fragment_home,container,false);
    fragmentActivity = new FragmentActivity();

    tabs = getResources().getStringArray(R.array.hometabs);
    viewPager = (ViewPager)rootView.findViewById(R.id.pager);
    actionBar = fragmentActivity.getActionBar();
    tabPagerAdapter = new TabPagerAdapter(fragmentActivity.getSupportFragmentManager());

    viewPager.setAdapter(tabPagerAdapter);
    actionBar.setHomeButtonEnabled(false);
    actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);

    for(String tab_name: tabs){
        actionBar.addTab(actionBar.newTab().setText(tab_name).setTabListener(this));
    }

    return rootView;
}

@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);

    getActivity().setTitle("Home");
}

@Override
public void onTabSelected(ActionBar.Tab tab, FragmentTransaction ft) {

}

@Override
public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction ft) {

}

@Override
public void onTabReselected(ActionBar.Tab tab, FragmentTransaction ft) {

}
}

行号40是actionbar = fragmentActivity.getActionBar();

有谁能告诉我为什么我会遇到这个问题?

2 个答案:

答案 0 :(得分:5)

而不是:

actionBar = fragmentActivity.getActionBar();

使用:

actionBar = getActivity().getActionBar();

初始化活动的方式

 fragmentActivity = new FragmentActivity();

不会提供有效的窗口装饰,以便从Activity获取操作栏。

答案 1 :(得分:0)

按如下方式更改onCreateView()方法

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                     Bundle savedInstanceState) {
    // Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.fragment_home,container,false);
fragmentActivity = getActivity();

tabs = getResources().getStringArray(R.array.hometabs);
viewPager = (ViewPager)rootView.findViewById(R.id.pager);
actionBar = fragmentActivity.getActionBar();
tabPagerAdapter = new TabPagerAdapter(fragmentActivity.getSupportFragmentManager());

viewPager.setAdapter(tabPagerAdapter);
actionBar.setHomeButtonEnabled(false);
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);

for(String tab_name: tabs){
    actionBar.addTab(actionBar.newTab().setText(tab_name).setTabListener(this));
}

return rootView;

}