-2

I have a fragment class:

public class UploadFragmentOne extends Fragment {}

I have subclassed:

 public interface Communicator {
        void communicate(int position);
    }

In the onCreateView:

 ((Communicator) getActivity()).communicate(1);

The hosting activity signature:

public class DetailsPager extends FragmentActivity implements UploadFragmentOne.Communicator {} 

Member function in the above activity:

 public void communicate(int position) {
        Toast.makeText(DetailsPager.this, "Clicked " + position, Toast.LENGTH_LONG).show();
    }

This works like a charm, but I dont understand HOW? Sorry this might be too dumb, but I want to know how the control flows in this?

User3
  • 2,465
  • 8
  • 41
  • 84
  • 1
    `can you tell what exactly you are not getting`? – Maveňツ Jul 23 '15 at 10:48
  • `((Communicator) getActivity()).communicate(1);` when I could have done it simply like `(MyActivity)activity.some_method().` – User3 Jul 23 '15 at 10:54
  • Please clarify your specific problem or add additional details to highlight exactly what you need. As it's currently written, it’s hard to tell exactly what you're asking. See the [How to Ask](http://stackoverflow.com/help/how-to-ask) page for help clarifying this question. – Maveňツ Jul 23 '15 at 11:40

1 Answers1

1

You should have a look on the following link once.- Now come to your query

(MyActivity)activity.some_method()

Now suppose you are going to attach the same fragment for another activity say MainActivity then you need to do like -

(MainActivity)activity.some_method()

Now suppose some other activity are implementing the same fragment then each time you need to use the instanceOf check and then call the method and also add it.

Again suppose a trivial case when you are going the create a library and you are going to offer some result delivery for the particular event then? How will you get the instance type ?

interface as the name suggests offer a way to be communicated without the actual class instance. They only need to be implemented. You can have a look on the OnClickListener in the View class of android API sources.

Community
  • 1
  • 1
Sanjeet A
  • 5,171
  • 3
  • 23
  • 40