Sending Data From Activity To Fragment
I have a side menu, when the side menu is pressed. It should take the SharedPreferences String and send it to the Fragment. And the Fragment should set the TextView and it will be
Solution 1:
Following issue is in current implementation :
1. If fragment_one
is in layout which return in from onCreateView
then use v
to call findViewById :
Viewv= inflater.inflate(R.layout.fragment_one, container, false);
textV = (TextView) getActivity().findViewById(R.id.frag_one_textview);
return v;
2. Call setTextV
after FT.commit();
:
FragmentTransaction FT = FM.beginTransaction();
FT.add(R.id.relative_main, F1);
FT.commit();
F1.setTextV(username);
Because you are getting value from SharedPreferences
to show in TextView so get value from Preferences in onCreateView
and show in TextView.
Solution 2:
In this particular case, you don't need to send data to the fragment because in a fragment you can access to SharedPreferences.
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
textV = (TextView) getActivity().findViewById(R.id.frag_one_textview);
Viewv= inflater.inflate(R.layout.fragment_one, container, false);
SharedPreferencessp= getActivity().getSharedPreferences("Login", Context.MODE_PRIVATE);
username = sp.getString("username", "DEFAULT");
textV.setText(username);
return v;
}
For other cases, the best way to send information from the Activity to the Fragment is using a Bundle.
if(num == 0)
{
SharedPreferencessp= getSharedPreferences("Login", Context.MODE_PRIVATE);
username = sp.getString("username", "DEFAULT");
FragmentOneF1=newFragmentOne();
Bundlebundle=newBundle();
bundle.putString("username", username);
// You can add all the information that you need in the same bundle
F1.setArguments(bundle);
FragmentManagerFM= getFragmentManager();
FragmentTransactionFT= FM.beginTransaction();
FT.add(R.id.relative_main, F1);
FT.commit();
}
Fragment:-
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
textV = (TextView) getActivity().findViewById(R.id.frag_one_textview);
Viewv= inflater.inflate(R.layout.fragment_one, container, false);
textV.setText(getArguments().getString("username", ""));
return v;
}
Post a Comment for "Sending Data From Activity To Fragment"