Reputation: 4981
I have 4 fragments inside my viewpager and I want to get the edit text value from another fragment. E.g :
I'm in the third fragment and I want to get the value of the Edit text inside the first fragment.
How can I do to do that ?
Upvotes: 1
Views: 2330
Reputation: 760
To do that you should pass your value through the constructor of your fragment.
For exemple you have your first fragment with a button that will call the secondFragment:
public class myFirstFragment extends Fragment implements View.OnClickListener {
private Button myButton;
private EditText myEdit;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.myFirstFragment_layout, container, false);
myButton = (Button) rootView.findViewById(R.id.buttonId);
myEdit = (EditText) rootView.findViewById(R.id.editTextId);
myButton.setOnClickListener(this);
return rootView;
}
@Override
public void onClick(View v) {
Fragment fragment;
switch (v.getId()) {
case R.id.buttonId:
fragment = new mySecondFragment(myEdit.getText().toString().trim());
break;
}
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction().replace(R.id.contenedor_frag, fragment).commit();
}
}
And in your second Class you should have this:
public class mySecondFragment extends Fragment {
private String myEditFirstFragment;
public mySecondFragment (String _editFirstFrag) {
this.myEditFirstFragment = _editFirstFrag;
}
}
Hope that helps,
Upvotes: 0
Reputation: 1524
In your MainActivity create a function and a global variable (setter and getter)
private EditText mEditText;
public EditText getEditText(){
return mEditText;
}
public void setEditText(EditText et){
this.mEditText = et;
}
In your FirstFragment
((MainActivity) getActivity()).setEditText(YOUR_EDITTEXT);
In your ThirdFragment where you need to get the EditText value
if( ((MainActivity) getActivity())getEditText() != null ){
((MainActivity) getActivity())getEditText().getText();
}
Upvotes: 0
Reputation: 1830
Interface is your best option.
As the fragment in viewpager is recreated every time. you cannot store values inside fragment and get it properly.
Create variable to hold editext value in ViewPager Hosting Activity.
String editext_fragment1;
Use Interface to write and get values from this variable from any fragments .
Upvotes: 1
Reputation: 3584
Try getActivity().findViewById()
, if you are not re-using the same id anywhere in other fragments. Check if it is null or not, then use it.
Hope it will help :)
Upvotes: 0