1

I have 3 fragments in another fragment, and I switch between fragments on a button click.
My issue that when I press the back button, the fragment is hidden and I need to press the back button again to exit the fragment.
How to solve this issue?

this is my fragment

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    if (rootView != null) {
        ViewGroup parent = (ViewGroup) rootView.getParent();
        if (parent != null)
            parent.removeView(rootView);
    }
    try {
        rootView = inflater.inflate(R.layout.barber_descrption_layout_fragment, container, false);
    } catch (InflateException e) {
    }
    context = getActivity();

    linearLayoutMain = (LinearLayout) rootView.findViewById(R.id.mainfrag);
    myTextView_appointment = (MyTextView) rootView.findViewById(R.id.text_appi);
    myTextView_map = (MyTextView) rootView.findViewById(R.id.textView2);
    myTextView_images = (MyTextView) rootView.findViewById(R.id.img);
    rate_btn = (LinearLayout) rootView.findViewById(R.id.rate_button);
    rate_btn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            ShowRateDialog(context);
        }
    });

    Fragment fragment = new Appointment_Fragment();
    Bundle bundle = new Bundle();
    fragment.setArguments(bundle);
    getActivity().getSupportFragmentManager().beginTransaction()
            .replace(R.id.mainfrag, fragment, fragment.getClass().getSimpleName()).addToBackStack(null).commit();
    linearLayoutMain.setBackground(getResources().getDrawable(R.drawable.blue_boarder_map));
    LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);

    linearLayoutMain.setLayoutParams(params);
    //////////////////////////////////
    myTextView_appointment.setBackground(getResources().getDrawable(R.drawable.appi_color));
    myTextView_appointment.setTextColor(getResources().getColor(R.color.white));
    /////////////////////////
    myTextView_appointment.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            myTextView_appointment.setBackground(getResources().getDrawable(R.drawable.appi_color));
            myTextView_appointment.setTextColor(getResources().getColor(R.color.white));
            myTextView_map.setTextColor(getResources().getColor(R.color.blue_color));
            myTextView_map.setBackground(getResources().getDrawable(R.drawable.map_color_white));
            myTextView_images.setTextColor(getResources().getColor(R.color.blue_color));
            myTextView_images.setBackground(getResources().getDrawable(R.drawable.blue__white));
            linearLayoutMain.setBackgroundColor(getResources().getColor(R.color.white));

            Fragment fragment = new Appointment_Fragment();
            Bundle bundle = new Bundle();
            fragment.setArguments(bundle);
            getActivity().getSupportFragmentManager().beginTransaction()
                    .replace(R.id.mainfrag, fragment, fragment.getClass().getSimpleName()).addToBackStack(null).commit();
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
            params.setMargins(0, 0, 0, 0);
            linearLayoutMain.setLayoutParams(params);

        }
    });
    myTextView_map.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            myTextView_map.setBackground(getResources().getDrawable(R.drawable.map_color));
            myTextView_map.setTextColor(getResources().getColor(R.color.white));
            myTextView_appointment.setTextColor(getResources().getColor(R.color.blue_color));
            myTextView_appointment.setBackground(getResources().getDrawable(R.drawable.apii_color_white));
            myTextView_images.setTextColor(getResources().getColor(R.color.blue_color));
            myTextView_images.setBackground(getResources().getDrawable(R.drawable.blue__white));
            linearLayoutMain.setBackground(getResources().getDrawable(R.drawable.blue_boarder_map));
            Fragment fragment = new MapFragment_Barber();
            Bundle bundle = new Bundle();
            fragment.setArguments(bundle);
            getActivity().getSupportFragmentManager().beginTransaction()
                    .replace(R.id.mainfrag, fragment, fragment.getClass().getSimpleName()).addToBackStack(null).commit();
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
            params.setMargins(40, 40, 40, 40);
            linearLayoutMain.setLayoutParams(params);

        }
    });

    myTextView_images.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            myTextView_images.setBackgroundColor(getResources().getColor(R.color.blue_color));
            myTextView_images.setTextColor(getResources().getColor(R.color.white));
            myTextView_map.setTextColor(getResources().getColor(R.color.blue_color));
            myTextView_map.setBackground(getResources().getDrawable(R.drawable.map_color_white));

            myTextView_appointment.setTextColor(getResources().getColor(R.color.blue_color));
            myTextView_appointment.setBackground(getResources().getDrawable(R.drawable.apii_color_white));
            linearLayoutMain.setBackgroundColor(getResources().getColor(R.color.white));
            Fragment fragment = new BarberImage();
            Bundle bundle = new Bundle();
            fragment.setArguments(bundle);
            getActivity().getSupportFragmentManager().beginTransaction()
                    .replace(R.id.mainfrag, fragment, fragment.getClass().getSimpleName()).addToBackStack(null).commit();

            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
            params.setMargins(40, 40, 40, 0);
            linearLayoutMain.setLayoutParams(params);
        }
    });

    return rootView;
}

I need so that when I press the back button I exit the fragment at the first click withiut the need of multiple clicks.

Phantômaxx
  • 37,901
  • 21
  • 84
  • 115
Moayed Alayaseh
  • 243
  • 7
  • 16

2 Answers2

0

Follow this. Its awesome example to implement onBackPressed() functionality on Fragment by using Abstract Class.

1) Create an Abstract Class -

import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;

public abstract class BackableFragment extends Fragment implements View.OnKeyListener {

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        view.setFocusableInTouchMode(true);
        view.requestFocus();
        view.setOnKeyListener(this);
    }

    @Override
    public boolean onKey(View v, int keyCode, KeyEvent event) {
        if (event.getAction() == KeyEvent.ACTION_UP) {
            if (keyCode == KeyEvent.KEYCODE_BACK) {
                onBackButtonPressed();
                return true;
            }
        }

        return false;
    }

    public abstract void onBackButtonPressed();
}

2) Implement the Abstract Class to your Fragment -

public class Appointment_Fragment extends BackableFragment {

public static final String CLASS_NAME = "Appointment_Fragment";
public FragmentChangeListener fragmentChangeListener;

    ...

    @Override
    public void onBackButtonPressed() {
        fragmentChangeListener.OnFragmentChange(CLASS_NAME);
    }

    ...
}

3) Make an interface with name FragmentChangeListener.

interface FragmentChangeListener{
     public void onFragmentChange(String fragmentName);
}

4) Implement it on your activity -

public class HomeActivity extends AppCompatActivity implements FragmentChangeListener{
........
.......
.......

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

            Fragment fragment = new Appointment_Fragment();
            fragment.fragmentChangeListener = this;
        Bundle bundle = new Bundle();
        fragment.setArguments(bundle);
        getActivity().getSupportFragmentManager().beginTransaction()
                .replace(R.id.mainfrag, fragment).commit(); //Always use getChildFragmentManager() for child fragment 
        }

@Override
    public void onFragmentChange(String fragmentName){
         if(fragmentName.equals("Appointment_Fragment")){
             //do what do you want 
         }else if(fragmentName.equals("FragmentB")){
            // do what do you want 
         }else if(fragmentName.equals("FragmentC")){
            //do what do you want 
         }
    }

}

Thats it. Reference

AGM Tazim
  • 2,213
  • 3
  • 16
  • 25
  • Make your parent `Frgament` as `BackableFragment` on which is the container of your 3 child Fragment. – AGM Tazim Oct 21 '17 at 10:13
  • Suppose you have multiple fragments. Calling Activity.onBackPressed in all of them will cause the activity to end when Back is pressed in any fragment. I suggest setting an OnBackPressedListener in the fragments, and have the Activity decide what to do when a particular fragment reports OnBackPressed. – Christine Oct 21 '17 at 10:20
  • then make an `interface` and implement it on your `activity`. You can send `Fragment` name to you `activity` from `BackableFragment''s on `onBackButtonPressed` method. – AGM Tazim Oct 21 '17 at 15:01
0

If you are in fragment then go for childFragmentManager

android.support.v4.app.FragmentManager fm = getChildFragmentManager();

on onBackPress just kill the parent fragment

Ankit Aman
  • 999
  • 6
  • 15
  • can u explain more ! i cannot understand this "onBackPress just kill the parent fragment" – Moayed Alayaseh Oct 22 '17 at 05:07
  • @MoayedAlayaseh your activity must be having one FragmentManager for parent fragment. on onBackpress of fragment call backpress of activity and check if fragment exist in fragment manager then pop the fragment from stack. So, if the parent get killed. child fragments will auto killed. – Ankit Aman Oct 22 '17 at 05:22
  • its not working ,,, i but this in main activity "android.support.v4.app.FragmentManager fm = getSupportFragmentManager();" because getChildFragmentManager(); its not on activity ,, and same issue not working !! – Moayed Alayaseh Oct 22 '17 at 05:36
  • if you are loading any fragment on top of any fragment then use childFragmentManager if its a activity the use fragmentManager – Ankit Aman Oct 22 '17 at 05:38