Back Button from Fragment to an another Fragment

921 views Asked by At

when I press on Back Button my app is closing, so I did some research about it, I found: How to handle back button in activity and How to catch device back button event in android? :

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
    if (keyCode == KeyEvent.KEYCODE_BACK ) {
        //do your stuff
    }
    return super.onKeyDown(keyCode, event);
}

But I get : "Cannot resolve method onKeyDown..."

My fragment:

public class NosOffres extends android.support.v4.app.Fragment {
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.activity_nosoffres, container, false);
        TextView firstTitle = (TextView) view.findViewById(R.id.firstTitle);
        firstTitle.setText(Html.fromHtml("<b>" + "<font color=#263355>RACHAT DE PR&Ecirc;TS IMMOBILIER</font>" + "</b>"));
        firstTitle.setTypeface(Typeface.createFromAsset(getActivity().getAssets(), "fonts/GothamBook.ttf"));
        TextView firstText = (TextView) view.findViewById(R.id.firstText);
        firstText.setText(Html.fromHtml("<font color=#5D5D5C>Op&eacute;ration qui permet de rassembler des cr&eacute;dits immobilier et des cr&eacute;dits &agrave; la consommation sur un seul nouveau contrat incluant une nouvelle dur&eacute;e de remboursement et une mensualit&eacute; r&eacute;duite.<br/><br/>Le financement est immobilier lorsque la part des encours immobiliers &agrave; reprendre est sup&eacute;rieure &agrave; 60% par rapport au total des capitaux &agrave; reprendre.</font>"));
        firstText.setTypeface(Typeface.createFromAsset(getActivity().getAssets(), "fonts/GothamBook.ttf"));
        TextView firstDetail = (TextView) view.findViewById(R.id.firstDetail);
        firstDetail.setText(Html.fromHtml("<font color=#263355>Taux :" + "<b>" + " fixe ou r&eacute;visable" + "</b><br/>" +
                "Dur&eacute;es :" + "<b>" + " de 60 &agrave; 420 mois" + "</b><br/>" +
                "Assurance :" + "<b>" + " facultative</font>" + "</b>"));
        firstDetail.setTypeface(Typeface.createFromAsset(getActivity().getAssets(), "fonts/GothamBook.ttf"));

        TextView secondTitle = (TextView) view.findViewById(R.id.secondTitle);
        secondTitle.setText(Html.fromHtml("<b>" + "<font color=#263355>RACHAT DE PR&Ecirc;TS CONSOMMATION</font>" + "</b>"));
        secondTitle.setTypeface(Typeface.createFromAsset(getActivity().getAssets(), "fonts/GothamBook.ttf"));
        TextView secondText = (TextView) view.findViewById(R.id.secondText);
        secondText.setText(Html.fromHtml("<font color=#5D5D5C>Op&eacute;ration qui permet de rassembler des cr&eacute;dits &agrave; la consommation sur un seul nouveau contrat incluant une nouvelle dur&eacute;e de remboursement et une mensualit&eacute; r&eacute;duite.<br/><br/>Le financement est &agrave; la consommation lorsque la part des encours immobiliers &agrave; reprendre est inf&eacute;rieure &agrave; 60% par rapport au total des capitaux &agrave; reprendre.</font>"));
        secondText.setTypeface(Typeface.createFromAsset(getActivity().getAssets(), "fonts/GothamBook.ttf"));
        TextView secondDetail = (TextView) view.findViewById(R.id.secondDetail);
        secondDetail.setText(Html.fromHtml("<font color=#263355>Taux :" + "<b>" + " fixe ou r&eacute;visable" + "</b><br/>" +
                "Dur&eacute;es :" + "<b>" + " &agrave; partir de 12 mois" + "</b><br/>" +
                "Assurance :" + "<b>" + " facultative</font>" + "</b>"));
        secondDetail.setTypeface(Typeface.createFromAsset(getActivity().getAssets(), "fonts/GothamBook.ttf"));
        TextView textView =(TextView)getActivity().findViewById(R.id.main_toolbar_title);
        textView.setText(getString(R.string.title_nosoffres));
        textView.setTypeface(Typeface.createFromAsset(getActivity().getAssets(), "fonts/GothamBook.ttf"));
        return view;
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        ImageView formulaire = (ImageView) getView().findViewById(R.id.formulaire);
        formulaire.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                startActivity(new Intent(Intent.ACTION_VIEW).setData(Uri.parse("http://www.solutis.fr/demande-rachat-credit.html/#utm_source=googleplay&utm_medium=application&utm_campaign=application-solutis-android")));
            }
        });
    }
}

I wan't to go in this fragment:

public class Accueil extends android.support.v4.app.Fragment {

    //Lors de la creation de la vue, on va attribuer a chaque zone de texte, le texte voulu avec un type particulier (font family...)
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        //placer ici le code pour connaitre la densite et la resolution de lecran
        View view = inflater.inflate(R.layout.activity_accueil, container, false);
        TextView topTextL1 = (TextView) view.findViewById(R.id.topTextL1);
        topTextL1.setText(Html.fromHtml("<font color=#263355>VOTRE EXPERT DU</font>"));
        topTextL1.setTypeface(Typeface.createFromAsset(getActivity().getAssets(), "fonts/GothamBook.ttf"));
        TextView topTextL2 = (TextView) view.findViewById(R.id.topTextL2);
        topTextL2.setText(Html.fromHtml("<b>" + "<font color=#263355> REGROUPEMENT DE CR&Eacute;DITS </font>" + "</b>"));
        topTextL2.setTypeface(Typeface.createFromAsset(getActivity().getAssets(), "fonts/GothamBook.ttf"));
        TextView topTextL3 = (TextView) view.findViewById(R.id.topTextL3);
        topTextL3.setText(Html.fromHtml("<font color=#263355>EN FRANCE DEPUIS </font><font color=#EF7A05>1998</font><font color=#263355>.</font>"));
        topTextL3.setTypeface(Typeface.createFromAsset(getActivity().getAssets(), "fonts/GothamBook.ttf"));
        TextView bottomText = (TextView) view.findViewById(R.id.bottomText);
        bottomText.setText(Html.fromHtml("<font color=#5D5D5C>Un cr&eacute;dit vous engage et doit &ecirc;tre rembours&eacute;. V&eacute;rifiez vos capacit&eacute;s de remboursement avant de vous engager.</font>"));
        bottomText.setTypeface(Typeface.createFromAsset(getActivity().getAssets(), "fonts/GothamBook.ttf"));
        return view;
    }

    //Apres creation de la vue ont va creer les evenements
    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        ImageView nosoffres = (ImageView) getView().findViewById(R.id.firstBlock);
        nosoffres.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                Fragment fragment = new NosOffres();
                FragmentManager fragmentManager = getFragmentManager();
                FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
                fragmentTransaction.replace(R.id.accueil, fragment);
                fragmentTransaction.commit();
            }
        });
        ImageView contact = (ImageView) getView().findViewById(R.id.secondBlock);
        contact.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                Fragment fragment = new ContactezNous();
                FragmentManager fragmentManager = getFragmentManager();
                FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
                fragmentTransaction.replace(R.id.accueil, fragment);
                fragmentTransaction.commit();
            }
        });
        ImageView actualites = (ImageView) getView().findViewById(R.id.thirdBlock);
        actualites.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                Fragment fragment = new Actualites();
                FragmentManager fragmentManager = getFragmentManager();
                FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
                fragmentTransaction.replace(R.id.accueil, fragment);
                fragmentTransaction.commit();
            }
        });
        ImageView mentions = (ImageView) getView().findViewById(R.id.fourthBlock);
        mentions.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                Fragment fragment = new MentionsLegales();
                FragmentManager fragmentManager = getFragmentManager();
                FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
                fragmentTransaction.replace(R.id.accueil, fragment);
                fragmentTransaction.commit();
            }
        });
        ImageView formulaire = (ImageView) getView().findViewById(R.id.formulaire);
        formulaire.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                startActivity(new Intent(Intent.ACTION_VIEW).setData(Uri.parse("http://www.solutis.fr/demande-rachat-credit.html/#utm_source=googleplay&utm_medium=application&utm_campaign=application-solutis-android")));
            }
        });
    }
}
2

There are 2 answers

7
NehaK On

create static fragment object-

public static Fragment currentFragment = null;

and initialize it in Activity/FragmentActivity class from where it is initializing

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
    if (keyCode == KeyEvent.KEYCODE_BACK ) {
        //do your stuff

        try{
            if(currentFragemnt!=null)
            {
                // do you work here respected to currentFragment
            }

        }
        catch(Exception e)
        {
            e.printStackTrace();
        }
    }
    currentFragemnt = null;
    return super.onKeyDown(keyCode, event);
}

So base activity will detect backPressed of device and perform task. Fragment can not detect backPressed only the activity on which they are attached detects it.

And Change setOnClickListener to-

nosoffres.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                currentFragment = new NosOffres();
                FragmentManager fragmentManager = getFragmentManager();
                FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
                fragmentTransaction.replace(R.id.accueil, fragment);
                fragmentTransaction.commit();
            }
        });
3
Anshuman Borah On

@Override onBackPressed() method of your FragmentActivity class

@Override
public void onBackPressed() {
    Log.d("back", "onBackPressed Called");

    // Do your stuff here
}