-2

I have a Relative layout and an ok button in mainActivity. On ok button click, a fragment will be added to this Relative layout. This Fragment has a cancel button.I want it to close that fragment on cancel button click.

public class filter_Fragment extends Fragment {

Button cancel;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){

        View rootView=inflater.inflate(R.layout.fragment_filter_,container, false);

        cancel=(Button)rootView.findViewById(R.id.cancel);
        cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v)
            {
            //Close fragment page. Return to mainActivity
         }
        });

  return rootView;
}
stan wyck
  • 9
  • 6
  • 1
    post some code please. – Rumit Patel Jan 31 '19 at 05:43
  • I have a cancel button inside the fragment when i click on it ,i want it to dismiss the fragment and go back to main ativity. – stan wyck Jan 31 '19 at 05:50
  • 1
    Ok. Update your question with your code also. – Rumit Patel Jan 31 '19 at 05:52
  • Please try to explore this link:- https://stackoverflow.com/questions/41127315/removing-a-fragment-from-a-fragment – DeePanShu Jan 31 '19 at 06:10
  • Thank you .But it's not working. I tried following code also ... cancel.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Fragment fragment= getActivity().getSupportFragmentManager().findFragmentById(R.id.layoutchange); fragmentTransaction=getActivity().getSupportFragmentManager().beginTransaction(); fragmentTransaction.remove(fragment); fragmentTransaction.commit(); } }); – stan wyck Jan 31 '19 at 06:17
  • It worked fine .but getting java.lang.NullPointerException: Attempt to invoke virtual method 'void android.support.v4.app.Fragment.setNextAnim(int)' on a null object reference... And app crashed – stan wyck Jan 31 '19 at 06:21
  • Please let me know your main activity contains any fragment?I mean your home fragment require any fragment? If so you need to replace with new fragment and if not you can call startActivity(new Intent(... – Farid Haq Jan 31 '19 at 07:07
  • I have a Relative layout and an ok button in mainActivity. On ok button click, a fragment will be added to this Relative layout. This Fragment has a cancel button.I want it to close that fragment on cancel button click. – stan wyck Jan 31 '19 at 07:19

2 Answers2

0

Try using this:

getFragmentManager().popBackStack();
dazed'n'confused
  • 231
  • 3
  • 13
-1

You better to close fragment contained activity on clicking close button in that fragment like below

getActivity().finish();
Ashok Reddy M
  • 330
  • 3
  • 9
  • Thank you. But this closes the application.I just need to close the fragment and go back to main activity on cancel button click. – stan wyck Jan 31 '19 at 06:40