Sunday
Sunday

Reputation: 117

How can I set onClick to close fragment in ImageView?

I cannot get this working using most of the solutions here. Please check my code that starts the fragment on the activity.

public void selectFrag() {
    Fragment fr;

    fr = new SelectionFragment();

    FragmentManager fm = getSupportFragmentManager();
    FragmentTransaction fragmentTransaction = fm.beginTransaction();
    //I removed this since my animations give error with FrameLayout
    //fragmentTransaction.setCustomAnimations(R.anim.slide_in_up, R.anim.slide_out_down);
    fragmentTransaction.replace(R.id.fragment_selection, fr);
    fragmentTransaction.commit();
}

On my fragment I have the following that is extending android.support.v4.app.Fragment;

public class SelectionFragment extends Fragment {

@Override
public View onCreateView(LayoutInflater inflater,
                         ViewGroup container, Bundle savedInstanceState) {
    //Inflate the layout for this fragment
    View view = inflater.from(getActivity()).inflate(
            R.layout.fragment_attributes, container, false);

    //Close fragment using close icon
    ImageView close = (ImageView) view.findViewById(R.id.close_fragment);
    close.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            closefragment();
        }
    });

    return view;
}//End onCreateView Method

private void closefragment() {
    getActivity().getFragmentManager().popBackStack();
}

}

My XML contains ImageView inside a RelativeLayout

<ImageView
            android:id="@+id/close_fragment"
            android:layout_width="30dp"
            android:layout_height="30dp"
            android:layout_alignParentRight="true"
            android:paddingTop="3dp"
            android:paddingRight="3dp"
            android:src="@drawable/close_cross"/>

How can I set ImageView to listen to click that closes the fragment? I have only one fragment and nothing happens with my code above.

Upvotes: 2

Views: 5039

Answers (4)

Neil
Neil

Reputation: 664

Solution is following:

fragmentTransaction.replace(R.id.fragment_selection, fr);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();`

Upvotes: 1

Zack
Zack

Reputation: 1574

Remove getActivity() from closefragment()

private void closefragment() {
    getFragmentManager().popBackStack();
}

Upvotes: 4

Alex
Alex

Reputation: 1

Try this pls.

private void closefragment() {
getParentFragment().getFragmentManager().popBackStack(); }

or this

private void closefragment() {
getActivity.finish(); }

Upvotes: 0

Jyotman Singh
Jyotman Singh

Reputation: 11340

popBackStack(); only reverses your previous transaction. If you want to close this Fragment you should call

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

Upvotes: 0

Related Questions