Reputation: 83
I have a viewpager containing 2 fragments and each fragment contains a edittext. When user clicks the button in the activity i need to get the edittext values in the fragments to activity. I referred to this documentation Communicating with Other Fragments, it is something like when user click the list item within the fragment i will get the values in the activity.But in my case the button is in activity.Could anyone suggest the right way of doing this
Upvotes: 3
Views: 5443
Reputation: 159
You can either do it like Christopher Francisco suggested (with TextWatchers) or you could assign IDs to the EditTexts and retrieve their data like this (in the Buttons onClickListener inside the Activity):
String editText1Data = ((EditText) findViewById(R.id.editText1)).getText().toString();
String editText2Data = ((EditText) findViewById(R.id.editText2)).getText().toString();
....
Upvotes: 5
Reputation: 16278
Instead of the Activity
asking the Fragment
for data, pass data from Fragment
to Activity
(without the need of it to ask).
What I mean is, add a TextWatcher
interface to the EditText
and afterTextChanged()
use an interface (read again http://developer.android.com/training/basics/fragments/communicating.html) to pass it to the Activity
. When the user press the button, you dont have to retrieve the value from the fragments, cause you already have them, you just have to apply the logic.
For example:
// Inside Activity, it should implement FragmentInterface1, FragmentInterface2
private String str1;
private String str2
@Override
public void onFragment1EditTextChanged(String string) {
str1 = string;
}
@Override
public void onFragment2EditTextChanged(String string) {
str2 = string;
}
// This is for each Fragment1 and Fragment2, just change the number acordingly
private FragmentInterface1 listener = null;
@Override
public View onCreateView(/*params*/) {
// inflate the view
edittext = (EditText) view.findViewById(R.id.myEditText);
edittext.addTextWatcher(new TextWatcher() {
// Any callback works, but i'd go for this one
public void afterTextChanged(/*params*/) {
if(listener != null) listener.onFragment1EditTextChanged(edittext.getText().toString());
}
});
}
@Override
public void onAttach(Activity activity) {
listener = (FragmentInterface1) activity;
}
public interface FragmentInterface1 {
public void onFragment1EditTextChanged(String string);
}
Upvotes: 2