Fragments addToBackStack Closing the application

2019-09-21 08:34发布

问题:

I am calling some fragments from HomeScreen.java. Now whenever i press back button in any fragment, its closes the application. But i want previous fragment which was loaded.Following is HomeScreen.java code.

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();
    }*/

}

So i have three menu icons, i am loading fragments from menu clicks.So please let me know something i did wrong.

回答1:

Suppose you have 3 fragments

(1) Fragment A

(2) Fragment B

(3) Fragment C

You are going A to B then B to C then Backpress will return to B then again Backpress will return to A then Backpress will close app.

Method for replace Fragment by adding Tag:

Pass your fragment and tag as arguments in below method.

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

No need to write onBackPress() or fragmentManager.popBackStack(), it will automatically handle.

Done



回答2:

Add this

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