Skip to content Skip to sidebar Skip to footer

Fragments Onclick Method In Fragment Element

I read quite some articles about fragments, but I am still confused about how to do what. I have a MainActivity, which displays two fragments side by side. In one of the fragments

Solution 1:

I'm not sure what the specific problem is, but maybe this will help.

From the Android documentation on Fragments:

You should design each fragment as a modular and reusable activity component. That is, because each fragment defines its own layout and its own behavior with its own lifecycle callbacks, you can include one fragment in multiple activities, so you should design for reuse and avoid directly manipulating one fragment from another fragment.

That is, you should never manipulate a fragment from another fragment; rather, this should be done through the underlying Activity. Read the "Creating event callbacks to the activity" section in this article for more information (it's important stuff!!).

On the other hand, if you want the button to perform an action within the Fragment itself (i.e. if you wanted a Button click to change the text of a TextView within the Fragment), you should implement this in the Fragment, not the Activity (this is because the resulting behavior is contained within the Fragment and has nothing to do with the parent Activity).

Leave a comment and I can clarify if my post is confusing... I only recently began to understand Fragment's myself :).

Solution 2:

Well,

I guess it is related to hierarchy of android context structure. Activity is host of all child views and hence you can say fragment is actually using its host's context.And that's why when you use onClick with fragment system always searches it in Host activity of fragment.

Check it on. Android developer onClick attribute description

I haven't checked one thing but you could put a test. By providing implementation in host activity rather than in fragment,but use onClick on layout file of fragment.It should call parent's method.

Post a Comment for "Fragments Onclick Method In Fragment Element"