AddToBackStack () method doesn't work without overriding onBackPressed () method in android

Here is the MainActivity code I wrote. I am loading a list of snippets on the first screen. When the user clicks on any of the list items, the planet's name will be displayed to the user in a detail snippet that I have defined in a separate class.

I add the "Planetary Planet List" → "Fragment Planet" transaction to the back stack. So what I expect is when I press the back button from the planet detail fragment, it should load the list of planets in the phone. But that doesn't happen.

import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.FrameLayout;

import com.meditab.fragments.fragment.FragmentPlanetDetail;
import com.meditab.fragments.fragment.FragmentPlanetList;

import java.util.ArrayList;
import java.util.List;


public class MainActivity extends ActionBarActivity implements Callback {

    private FrameLayout frmPlanetList;
    private FrameLayout frmPlanetDetail;
    private boolean isPhone;


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

        frmPlanetList = (FrameLayout) findViewById(R.id.frmPlanetList);
        frmPlanetDetail = (FrameLayout) findViewById(R.id.frmPlanetDetail);

        if (null != frmPlanetDetail) {
            isPhone = false;
        } else {
            isPhone = true;
        }

        FragmentManager fragmentManager = getFragmentManager();

        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();

        fragmentTransaction.replace(R.id.frmPlanetList, new FragmentPlanetList());

        fragmentTransaction.commit();

    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onListItemClicked(int intPosition) {

        FragmentManager fragmentManager = getFragmentManager();

        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();

        List<String> lstPlanetArray = getPlanetArray();
        String strPlanetName = lstPlanetArray.get(intPosition);

        FragmentPlanetDetail fragmentPlanetDetail = FragmentPlanetDetail.newInstance(strPlanetName);
        if (isPhone) {
            fragmentTransaction.addToBackStack(null);
            fragmentTransaction.replace(R.id.frmPlanetList, fragmentPlanetDetail);
        } else {
            fragmentTransaction.replace(R.id.frmPlanetDetail, fragmentPlanetDetail);
        }

        fragmentTransaction.commit();

    }

    private List<String> getPlanetArray() {
        List<String> lstPlanets = new ArrayList<>(10);
        lstPlanets.add("Mercury");
        lstPlanets.add("Venus");
        lstPlanets.add("Earth");
        lstPlanets.add("Mars");
        lstPlanets.add("Jupiter");
        lstPlanets.add("Saturn");
        lstPlanets.add("Uranus");
        lstPlanets.add("Neptune");
        lstPlanets.add("Saturn");

        return lstPlanets;
    }

}

      

However, if I override the backPress method and reverse it programmatically, it works fine.

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

      

Do I need to override the onBackPressed () method in this way if I want to achieve this? Not specified that you need to override this method from this link. Android Back Press Fragment Documentation

Detailed planetary planet class

import android.app.Fragment;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.meditab.fragments.R;

/**
 * Created by BHARGAV on 25-Dec-14.
 */
public class FragmentPlanetDetail extends Fragment {

    private String strPlanetName;

    public FragmentPlanetDetail() {

    }

    public static FragmentPlanetDetail newInstance(String strPlanetName) {
        FragmentPlanetDetail fragmentPlanetDetail = new FragmentPlanetDetail();

        Bundle bundle = new Bundle();
        bundle.putString("Planet_Name", strPlanetName);
        fragmentPlanetDetail.setArguments(bundle);
        return fragmentPlanetDetail;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        Bundle bundle = getArguments();
        if (null != bundle) {
            strPlanetName = bundle.getString("Planet_Name");
        }
    }

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

        TextView txtPlanetName = (TextView) rootView.findViewById(R.id.txtPlanetName);
        txtPlanetName.setText(strPlanetName);

        return rootView;
    }
}

      

List of planetary planet classes:

import android.app.Activity;
import android.app.Fragment;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;

import com.meditab.fragments.Callback;
import com.meditab.fragments.R;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by BHARGAV on 25-Dec-14.
 */
public class FragmentPlanetList extends Fragment {

    private ListView listView;
    private ArrayAdapter<String> stringArrayAdapter;

    private Callback callback;


    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        final View rootView = inflater.inflate(R.layout.listview, container, false);

        listView = (ListView) rootView.findViewById(R.id.listView);
        stringArrayAdapter = new ArrayAdapter<>(getActivity(),
                android.R.layout.simple_list_item_1, getPlanetArray());
        listView.setAdapter(stringArrayAdapter);

        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                callback.onListItemClicked(position);
            }
        });
        return rootView;
    }



    @Override
    public void onAttach(Activity activity) {

        super.onAttach(activity);

        callback = (Callback) activity;
    }

    private List<String> getPlanetArray() {
        List<String> lstPlanets = new ArrayList<>(5);
        lstPlanets.add("Mercury");
        lstPlanets.add("Venus");
        lstPlanets.add("Earth");
        lstPlanets.add("Mars");
        lstPlanets.add("Jupiter");
        lstPlanets.add("Saturn");
        lstPlanets.add("Uranus");
        lstPlanets.add("Neptune");
        lstPlanets.add("Saturn");

        return lstPlanets;
    }

}

      

Callback interface:

/**
 * Created by BHARGAV on 26-Dec-14.
 */
public interface Callback {

    public void onListItemClicked(int intPosition);
}

      

Thank. Please let me know if any additional details or code is needed.

+3


source to share


5 answers


Ok. So the reason it doesn't work is because the difference between ActionBarActivty and Activity is conflicting. And the difference between getSupportFragmentManager () and getFragmentManager () FragmentTransaction methods .

ActionBarActivity:

I used ActionBarActivity which android.support.v7.app.ActionBarActivity

. This means I was using the v7 compat library

FragmentManager: The fragment manager was not from the compatibility library. It was straight

import android.app.FragmentManager;
import android.app.FragmentTransaction;

      



as you can see in the MainActivity class.

Detail: android.app.Fragment

; it is a class that is imported into individual fragment classes.

So as soon as I moved from ActionBarActivity to Activity class everything was fine. The same is true if I changed the FragmentManager, FragmentTransaction and Fragment classes to support library classes.

So, after any modification, everything began to work fine. Thank.

+6


source


You don't need to override the method, of course onBackPressed()

. It's just a hack.

Your condition is messed up.



if (isPhone) {
        fragmentTransaction.addToBackStack(null);

      

why don't you use this operator unconditionally to make sure it works. You can remain calm as is. Just move this statement outside of the if condition.

0


source


Wierd but i think

addToBackStack(null)

      

- problem

Try it with

addToBackStack("planetDetail");

      

0


source


You are using an actionbar which extends the fragment's activity. Now, to have perfect behavior, you need support snippets to work with actions in the action bar.

This is where you work with normal fragment actions (don't support v4 fragments) and what is causing the problem. To have the perfect behavior, change your fragments to support fragments and it should work fine.

Let me know if this doesn't work.

0


source


Okay, I had the same problem with you. What worked for me and I think his solution for you too is to change:

1.fragment a snippet from the support library:

import android.support.v4.app.Fragment;

      

and

  1. getFragmentManager () with getSupportFragmentManager ():
0


source







All Articles