Pavel Petrashov
Pavel Petrashov

Reputation: 257

How can I close the fragment?

I am have Fragment on the Activity. Fragment has button. if i click on the button, Fragment must be close. How i am did this?

public class ItemFragment extends Fragment{

    private ImageView btnApply;
    private ClickButton clickButton = new ClickButton();

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.item_info, container, false);
        btnApply = (ImageView) rootView.findViewById(R.id.btnSendItem);
        btnApply.setOnClickListener(clickButton);
        return rootView;
    }

    private class ClickButton implements View.OnClickListener {

        @Override
        public void onClick(View v) {
            if (R.id.btnSendItem == v.getId()) {
                Toast.makeText(getActivity(),"CLOSE",Toast.LENGTH_LONG).show();
                return;
            }
        }
    }
}

Upvotes: 6

Views: 20799

Answers (2)

Ben
Ben

Reputation: 423

When this fragment is of type androidx.fragment.app.Fragment then this seems to work:

getActivity().getFragmentManager().popBackStack();

This pops the top visible fragment off the stack.

Upvotes: -1

Apurva
Apurva

Reputation: 7901

There's no such thing like close the fragment, but you can remove the fragment from the stack. To pop the fragment use the following inside button click listener

getActivity().getFragmentManager().beginTransaction().remove(this).commit();

Upvotes: 14

Related Questions