Given:

  • From a fragment, you can always call getActivity() to get a reference to the activity in context.
    • And of course, you can you can cast this instance to a strong type (like MainActivity) to get references to public properties and public methods on the activity.

My Question:

  • Is this bad form? Should it be avoided?
    • Specifically, should references to properties and methods on an activity be acquired via interfaces?
  • Or is it standard practice to expose public properties and methods to fragments from an activity?
有帮助吗?

解决方案

should references to properties and methods on an activity be acquired via interfaces?

It helps future-proof your code, if the fragment might be hosted by some other activity later on (e.g., one activity used in a phone-sized form factor, a different activity used in a tablet-sized form factor). It is not that difficult to set up a contract interface.

is it standard practice to expose public properties and methods to fragments from an activity?

This seems to be the same question you just asked. Though note that whether they need to be public, or can remain package-private, depends on whether they are in the same package.

If I misinterpreted this second question, I apologize, but you might want to clarify it a bit.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top