androidtitan
androidtitan

Reputation: 671

Android: Why is your Activity cast to your Fragment/Activity Interface when setting your Interface?

I am working on passing an integer from one fragment to another. I am pretty sure I understand the concept of passing the value to the Activity through an Interface and then handing that value down to the Fragment.

I can get it to work just copying code following the example here http://developer.android.com/training/basics/fragments/communicating.html . For an example, I declare my Interface in the Fragment as Interface mCallback; and in the onAttach() method of the same fragment this line of code is executed mCallback = (Interface) activity;

Could someone explain why the interface is set as a cast activity and why it is done this way?

Upvotes: 0

Views: 98

Answers (2)

tritop
tritop

Reputation: 1745

The comment says it all. Its not that the Interface is set as a cast Activity, it's the other way around. It is just a check: If the Activity is implementing the Interface/Listener you will be able to cast it to the Interface. If it isn't, it will fail and the Exception will be thrown. Thats because by implementing the Interface it is guaranteed that the Activity has all methods the Interface has. If it is not castable to the Interface, it has not implemented the Interface. The casted Activity is a 'Activity light', it only has the methods the Interface has, while losing all other methods of your Activity.

Upvotes: 0

Marcin Orlowski
Marcin Orlowski

Reputation: 75647

Could someone explain why the interface is set as a cast activity and why it is done this way?

This is done to ensure given activity implements interface you are expecting it to implement. If it does so, all is fine, you can keep going, most likely call methods you can expect present due to interface implementation. If activity does not implement given interface, exception is thrown so your app either crash or you can handle this case somehow - nonetheless in most cases this is a bug.

Upvotes: 1

Related Questions