处理带有片段和活动的后退按钮?

时间:2015-07-03 23:55:54

标签: android android-fragments

我有一个"活动A"启动两个片段,主页按钮是活动A的一部分,当从createFragment按下后退按钮时,它应该返回到活动A之前的活动,它使用finish()方法做得很好但是当我有第二个片段,followersFragment,它添加在createFragment的ontop上并隐藏了createFragment(因为我不希望信息在创建中丢失),然后我点击后退按钮然后切换回创建片段但是当我点击时来自createFragment的后退按钮它不会再回到活动A而且什么都不做......没有错误...

这是我保存片段(不是活动A)的活动的代码:

@Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar actions click
        switch (item.getItemId()) {
            // lets user travel back to where they came from
            case android.R.id.home:
                if(displayShown == 1) {

                    displayView(2, 0);
                } else {

                }
                return true;

private void displayView(int i, int position) {

        Log.d(Constants.DEBUG, "display view called " +position);
        boolean createPost = true;
        // update the main content by replacing fragments
        Fragment fragment = null;
        switch (position) {
            case 0:
                //avoid recreating createPostFragment if already created because all data will be erased
                if(createPostFragment == null){
                    createPost = false;
                    Log.d(Constants.DEBUG, "fragment create DOES NOT EXIST ");
                    createPostFragment = new CreatePostFragment();
                }



                fragment = createPostFragment;
                break;
            case 1:
                followerFragment = new FollowerFragment();
                fragment = followerFragment;
                break;
            default:
                break;
        }

        if (fragment != null) {

            FragmentManager fragmentManager = getFragmentManager();
            trans = fragmentManager.beginTransaction();


            //if createpostfrag already created just show
            if (createPost && position == 0) {
                trans.remove(followerFragment);
                trans.show(createPostFragment);
                trans.commit();


                //hide createpostfrag so we can reuse
            } else {
                if(position == 1) {
                    Bundle extraData = new Bundle();
                    extraData.putInt("follow", i);
                    fragment.setArguments(extraData);

                    trans.add(R.id.frame_container, fragment, null).commit();
                    trans.hide(createPostFragment);
                }

                if(position == 0) {

                    trans.add(R.id.frame_container, fragment, "keepAlive").commit();
                }

            }

        } else {
            // error in creating fragment
            Log.d(Constants.DEBUG, "Error in creating fragment or no fragment needed");
        }
    }

0 个答案:

没有答案