Fragments addToBackStack 关闭应用程序

Fragments addToBackStack Closing the application

我正在调用 HomeScreen.java 中的一些片段。现在,每当我在任何片段中按下后退按钮时,它都会关闭应用程序。但我想要之前的 loaded.Following 片段是 HomeScreen.java 代码。

public class HomeScreen extends AppCompatActivity implements JobListFragment.OnJobSelectedListener {



    Timer timer;
    TimerTask timerTask;
    final android.os.Handler handler = new android.os.Handler();

    FragmentTransaction transaction;
    android.app.FragmentManager fragmentManager;
    ProfileFragment profileFragment;
    HomeFragment homeFragment;
    LocationFragment locationFragment;
    JobListFragment jobListFragment;
    JobDetailsFragment jobDetailsFragment;

    ActionBar actionBar;
    Toolbar toolbar;

    Fragment fragment;




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

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

        actionBar = getSupportActionBar();

        KitLocate.initKitLocate(HomeScreen.this, "f08fb7d8-bc35-46c6-aaad-07657eb4a59c");
        KitLocate.setUniqueUserID(HomeScreen.this, Utils.getUniqueId(HomeScreen.this));
        String onlineStatus = Utils.getStringPref(HomeScreen.this, Constants.onlineStatus);

        profileFragment =new ProfileFragment();
        homeFragment = new HomeFragment();
        locationFragment=new LocationFragment();

        jobListFragment = new JobListFragment();
        jobDetailsFragment = new JobDetailsFragment();
        fragmentManager =  getFragmentManager();
        transaction = fragmentManager.beginTransaction();
        transaction.add(R.id.fragmentContainer, homeFragment);

        transaction.commit();




    }

    public void startTimer() {
        //set a new Timer
        timer = new Timer();

        //initialize the TimerTask's job
        initializeTimerTask();

        //schedule the timer, after the first 5000ms the TimerTask will run every 10000ms
        timer.schedule(timerTask, 1000, 10000); //
    }

    public void stoptimertask(View v) {
        //stop the timer, if it's not already null
        if (timer != null) {
            timer.cancel();
            timer = null;
        }
    }

    public void initializeTimerTask() {

        timerTask = new TimerTask() {
            public void run() {

                //use a handler to run a toast that shows the current timestamp
                handler.post(new Runnable() {
                    public void run() {
                        String locality = PeriodicHandler.getInstance().getLocality();
                        String subLocality = PeriodicHandler.getInstance().getSubLocality();

                        LocationFragment locationFrag = (LocationFragment)
                                getFragmentManager().findFragmentById(R.id.fragmentContainer);
                        /*if(locationFrag != null){
                            System.out.println();
                            locationFrag.updateLocationText();
                        }*/


                    }
                });
            }
        };
    }


    @Override
    public void onJObSelected(int position, String jobId) {
        fragmentManager =  getFragmentManager();
        transaction = fragmentManager.beginTransaction();
        jobDetailsFragment = new JobDetailsFragment();
        if(jobDetailsFragment.isAdded() || jobDetailsFragment.isHidden()){
            System.out.println("44444444444444444444");
            Bundle bundle = new Bundle();
            bundle.putString(Constants.jobID, jobId);
            jobDetailsFragment.setArguments(bundle);
            transaction.replace(R.id.fragmentContainer, jobDetailsFragment);
            transaction.addToBackStack(null);

        }else{


            Bundle bundle = new Bundle();
            bundle.putString(Constants.jobID, jobId);
            jobDetailsFragment.setArguments(bundle);
            transaction.add(R.id.fragmentContainer, jobDetailsFragment);//transaction.show(profileFragment);

        }
        transaction.commit();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.home_menu, menu);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch(item.getItemId()) {

            case R.id.action_account:
                actionBar.setDisplayShowHomeEnabled(false);
                actionBar.setDisplayHomeAsUpEnabled(true);
                actionBar.setHomeButtonEnabled(true);

                fragmentManager =  getFragmentManager();
                transaction = fragmentManager.beginTransaction();
                System.out.println("isadded"+profileFragment.isAdded()+"isHidden"+profileFragment.isHidden());
                if(profileFragment.isAdded() || profileFragment.isHidden()) {
                    /*transaction.show(profileFragment);
                    transaction.hide(locationFragment);*/
                    profileFragment = new ProfileFragment();
                    transaction.replace(R.id.fragmentContainer, profileFragment, LocationFragment.TAG);
                    transaction.addToBackStack("account");
                }else{
                    transaction.add(R.id.fragmentContainer, profileFragment);//transaction.show(profileFragment);
                }
                transaction.commit();
                break;
            case R.id.action_profile_location:
                actionBar.setDisplayShowHomeEnabled(false);
                actionBar.setDisplayHomeAsUpEnabled(true);
                actionBar.setHomeButtonEnabled(true);

                fragmentManager =  getFragmentManager();
                transaction = fragmentManager.beginTransaction();
                System.out.println("isadded"+locationFragment.isAdded()+"isHidden"+locationFragment.isHidden());
                if(locationFragment.isAdded() || locationFragment.isHidden()) {
                    /*transaction.show(locationFragment);
                    transaction.hide(profileFragment);*/
                    locationFragment = new LocationFragment();
                    transaction.replace(R.id.fragmentContainer, locationFragment);
                    transaction.addToBackStack(null);
                }
                else{
                    transaction.add(R.id.fragmentContainer, locationFragment);//transaction.show(profileFragment);

                }
                transaction.commit();
                break;
            case R.id.action_profile_time:
                actionBar.setDisplayShowHomeEnabled(false);
                actionBar.setDisplayHomeAsUpEnabled(true);
                actionBar.setHomeButtonEnabled(true);

                fragmentManager =  getFragmentManager();
                transaction = fragmentManager.beginTransaction();
                System.out.println("isadded" + jobListFragment.isAdded() + "isHidden" + jobListFragment.isHidden());
                if(jobListFragment.isAdded() || jobListFragment.isHidden()){
                    System.out.println("111111111111111111");
                    // transaction.show(jobListFragment);
                    jobListFragment = new JobListFragment();
                    transaction.replace(R.id.fragmentContainer, jobListFragment);
                    transaction.addToBackStack("profile");

                }else{
                    transaction.add(R.id.fragmentContainer, jobListFragment);//transaction.show(profileFragment);
                }
                transaction.commit();
                break;
            case android.R.id.home:
                actionBar.setDisplayShowHomeEnabled(false);
                actionBar.setDisplayHomeAsUpEnabled(false);
                actionBar.setHomeButtonEnabled(false);
                fragmentManager =  getFragmentManager();
                transaction = fragmentManager.beginTransaction();
                System.out.println("isadded"+homeFragment.isAdded()+"isHidden"+homeFragment.isHidden());
                if(homeFragment.isAdded() || homeFragment.isHidden()){
                    System.out.println("55555555555555555");
                    //transaction.remove(homeFragment);
                    //transaction.add(R.id.fragmentContainer, homeFragment);
                    //transaction.show(homeFragment);
                    homeFragment = new HomeFragment();
                    transaction.replace(R.id.fragmentContainer, homeFragment);
                    transaction.addToBackStack("home");
                }else{
                    transaction.add(R.id.fragmentContainer, homeFragment);//transaction.show(profileFragment);
                }
                transaction.commit();
                break;

        }
        return true;
    }
   /*@Override
    public void onBackPressed() {
        if (getFragmentManager().popBackStackImmediate()) return;
            if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP)
                finish();
        else
            finishAfterTransition();
    }*/

}

所以我有三个菜单图标,我正在从菜单中加载片段clicks.So请让我知道我做错了什么。

添加这个

@Override
public void onBackPressed() {
   if (getFragmentManager().getBackStackEntryCount() > 0) {
       getFragmentManager().popBackStack();
   }
   else
   {
       super.onBackPressed;
   }
}

假设你有3个碎片

(1) 片段 A

(2) 片段 B

(3) 片段 C

你要A到B然后B到C然后Backpressreturn 到 B 然后 Backpressreturn 到 A 然后 Backpress关闭应用程序

通过添加 Tag 替换 Fragment 的方法:

将您的片段和标记作为参数传递到以下方法中。

private void replaceFragment(Fragment frag, String tag) {
    FragmentTransaction transaction = getFragmentManager().beginTransaction();
    transaction.replace(R.id.realtabcontent, frag);
    transaction.addToBackStack(tag);
    transaction.commitAllowingStateLoss();
}

不需要onBackPress()fragmentManager.popBackStack() , 它将自动处理。

完成