Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can I refer to a fragment from a class implemented inside it?

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);

        }
    }
}

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Just refer to the enclosing class this:

  Fragment f = MapFragment.this;
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading