Home > front end >  How can I refer to a fragment from a class implemented inside it?
How can I refer to a fragment from a class implemented inside it?

Time:05-10

I have an activity with some fragments of the same type. In fragments I have a list. As soon as I click on a list item, I need to invoke an activity method, passing the fragment where the click took place.

I think this is a rather silly question, but I can't figure it out.

public class MapFragment extends Fragment {

    Activity activity;

    public void onAttach(Activity activity) {
        super.onAttach(activity);
        this.activity = activity;
    }

    public MapFragment() {
        /* here I could refer to the fragment using "this" */
    }

    private class MyListOnItemClick implements AdapterView.OnItemClickListener {

        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

            /* how can I refer to the fragment here?  */

            Fragment f = getFragmentSomeWay();

            (CustomActivity)activity.doSomethingWith(f);

        }
    }
}

CodePudding user response:

Just refer to the enclosing class this:

  Fragment f = MapFragment.this;

CodePudding user response:

Your Fragment can implement AdapterView.OnItemClickListener.

public class MapFragment extends Fragment implements AdapterView.OnItemClickListener {

  @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
           requireActivity().doSomethingWith(f);

        }

Some people would actually just use an anonymous class here.

 adapter.setOnItemClickListener(AdapterView.OnItemClickListener listener = new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(final AdapterView<?> adapterView, final View view, final int i, final long l) {
                requireActivity().doStuff();
            }
        };
  • Related