Reputation: 865
I have been looking and scouring around the web, even tried to check the official Android doc for "communicating between fragments" or communicating with fragment and activity (http://developer.android.com/training/basics/fragments/communicating.html), and even tried searching a few questions here at StackOverflow just to get a hint to my problem, but none of them seem to answer my case.
I know of the interface listener that is implemented by a host Activity
to pass data from Fragment
to the host Activity
, and used it A LOT in my projects. But I think that model of fragment data passing is actually useful only if there is a "meta" event i.e. onClick
, onItemClick
, etc) that would fire that custom event.
But for my case, I have a Fragment containing RadioGroup
, with the RadioGroup
's content, first of which is a view group with several EditText
s, in which I need to send its contents back to the Fragment's host Activity with several other objects. My custom event is being fire by a "meta" event, that is, the RadioGroup.setOnCheckedChangeListener()
.
To visualize, this is how it is layed out in my layout resource:
RadioGroup
-RadioButton 1
--- LinearLayout (which is toggled to be shown by checking RadioButton 1, hidden when other RadioButton is checked) containing several EditText s
------EditText 1
------EditText 2
------EditText 3
------EditText 4
-RadioButton 2
-RadioButton 3
-RadioButton 4
Every time I check RadioButton 1, it toggles to show the LinearLayout with the EditText, obviously it fires setOnCheckedChangeListener() of the RadioGroup, within which it fires my custom event with parameters like a custom object with contents coming from the EditText s. HOWEVER, my custom event won't be called when I don't check the RadioGroup and when I edit/update the EditText.
I think of using EditText.addTextChangedListener()
on those EditText
s and fire my custom event whenever I fill all the data on my form. But I think it's a bit not elegant to do that, and I guess there would be a more elegant and better, if any, way of passing those EditText data from their host fragment back to the Activity, or may be to get the data from Fragment in to the Activity
My question is, how do I pass OR get data FROM fragment to Activity in which I won't depend on "meta" events to fire my custom event or in some other way around.
Upvotes: 0
Views: 162
Reputation: 83537
To communicate back to my activities, I simply add a method which the fragment can call directly. In the Activity class:
public void sendMessage(String message) {
// Do something with the message
}
In the fragment:
((MyActivity)getActivity()).sendMessage("Code Apprentice is the best!");
Upvotes: 1