在片段中添加后退箭头

时间:2016-06-10 07:02:37

标签: android android-toolbar

我在MainActivity中有一个framelayout,并且我已将TabFragment片段附加到活动中。 TabFragment具有TabLayout以及导航抽屉。我在TabFragment中使用了这个链接推荐的样式工具栏的答案。但是当我在NewFragment中使用((AppCompatActivity)getActivity()).getSupportActionBar().setDisplayHomeAsUpEnabled(true);时(它会在按钮上单击其中一个选项卡时打开),应用程序崩溃并显示NullPointerException。我想要后箭头而不使用任何可绘制的图标。感谢您在这方面的任何帮助。

FATAL EXCEPTION: main
                                                                    Process: com.sam.pagersliding, PID: 7652
                                                                    java.lang.NullPointerException
                                                                        at com.sam.pagersliding.NewFragment.onCreate(NewFragment.java:27)
                                                                        at android.support.v4.app.Fragment.performCreate(Fragment.java:1951)
                                                                        at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1029)
                                                                        at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1252)
                                                                        at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:742)
                                                                        at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1617)
                                                                        at android.support.v4.app.FragmentManagerImpl$1.run(FragmentManager.java:517)
                                                                        at android.os.Handler.handleCallback(Handler.java:808)
                                                                        at android.os.Handler.dispatchMessage(Handler.java:103)
                                                                        at android.os.Looper.loop(Looper.java:193)
                                                                        at android.app.ActivityThread.main(ActivityThread.java:5388)
                                                                        at java.lang.reflect.Method.invokeNative(Native Method)
                                                                        at java.lang.reflect.Method.invoke(Method.java:515)
                                                                        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
                                                                        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:655)
                                                                        at dalvik.system.NativeStart.main(Native Method)

public class NewFragment extends Fragment{

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        ((AppCompatActivity)getActivity()).getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        setHasOptionsMenu(true);
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.newfrag, container, false);
    }

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

    }




    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        switch (id){
            case android.R.id.home:
                getActivity().onBackPressed();
                break;
        }
        return super.onOptionsItemSelected(item);
    }



}
public class TabFragment extends Fragment{

    Toolbar toolbar;
    private TabLayout tabLayout;
    private ViewPager viewPager;

    public static DrawerLayout mDrawerLayout;
    NavigationView navigationView;
    ActionBarDrawerToggle mDrawerToggle;


    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.tabfrag, container, false);


    }

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

        toolbar = (Toolbar) view.findViewById(R.id.toolbar);
        tabLayout = (TabLayout) view.findViewById(R.id.tabs);
        viewPager = (ViewPager) view.findViewById(R.id.viewpager);
        mDrawerLayout = (DrawerLayout) view.findViewById(R.id.drawer_layout);
        navigationView = (NavigationView) view.findViewById(R.id.navigation_view);

        setupViewPager(viewPager);
        tabLayout.setupWithViewPager(viewPager);

        mDrawerToggle = new ActionBarDrawerToggle(getActivity(),mDrawerLayout, toolbar,R.string.app_name,R.string.app_name);
        mDrawerToggle.syncState();

        navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
            @Override
            public boolean onNavigationItemSelected(MenuItem menuItem) {
                mDrawerLayout.closeDrawers();



                if (menuItem.getItemId() == R.id.nav_one) {
                    NavOne nav1 = new NavOne();
                    ((MainActivity)getActivity()).replaceFragment(nav1);
                    mDrawerLayout.closeDrawer(navigationView);

                }

                if (menuItem.getItemId() == R.id.nav_two) {
                    NavTwo nav2 = new NavTwo();
                    ((MainActivity)getActivity()).replaceFragment(nav2);
                    mDrawerLayout.closeDrawer(navigationView);

                }

                return false;
            }

        });
    }

    private void setupViewPager(ViewPager viewPager) {
        ViewPagerAdapter adapter = new ViewPagerAdapter(getChildFragmentManager());
        adapter.addFragment(new OneFragment(), "ONE");
        adapter.addFragment(new TwoFragment(), "TWO");
        viewPager.setAdapter(adapter);
    }

    class ViewPagerAdapter extends FragmentPagerAdapter {
        private final List<Fragment> mFragmentList = new ArrayList<>();
        private final List<String> mFragmentTitleList = new ArrayList<>();

        public ViewPagerAdapter(FragmentManager manager) {
            super(manager);
        }

        @Override
        public Fragment getItem(int position) {
            return mFragmentList.get(position);
        }

        @Override
        public int getCount() {
            return mFragmentList.size();
        }

        public void addFragment(Fragment fragment, String title) {
            mFragmentList.add(fragment);
            mFragmentTitleList.add(title);
        }

        @Override
        public CharSequence getPageTitle(int position) {
            return mFragmentTitleList.get(position);
        }
    }
}
public class MainActivity extends AppCompatActivity {

    FragmentManager myFragmentManager;
    FragmentTransaction myFragmentTransaction;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // Attach main fragment to activity
        if (findViewById(R.id.containerView) != null) {
            if (savedInstanceState != null) {
                return;
            }

            myFragmentManager = getSupportFragmentManager();
            myFragmentTransaction = myFragmentManager.beginTransaction();
            myFragmentTransaction.replace(R.id.containerView, new TabFragment()).commit();
        }



    }

    public void replaceFragment(Fragment fragment){
        FragmentTransaction t = getSupportFragmentManager().beginTransaction();
        t.replace(R.id.containerView, fragment).addToBackStack(null);
        t.commit();
    }



}

3 个答案:

答案 0 :(得分:2)

不要从布局中获取片段中的工具栏,而是尝试从MainActivity中引用它:

toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);

然后在片段中使用:

     ((AppCompatActivity)getActivity()).getSupportActionBar().setDisplayHomeAsUpEnabled(true);

答案 1 :(得分:1)

应启用以下两项功能

getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);

连同设置后退按钮

@Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                this.finish();
                return true;
            default:
                return false;
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        return false;
    }

答案 2 :(得分:0)

删除此行

((AppCompatActivity)getActivity()).getSupportActionBar().setDisplayHomeAsUpEnabled(true);

来自onActivityCreated

尝试在简历中使用它

((AppCompatActivity)getView().getContext())getActivity()).getSupportActionBar().setDisplayHomeAsUpEnabled(true);