I want to send String
data from fragment
to activity
.
I have read the article about communicating between fragment and activity in android developer, using onAttach
callback.
can anyone explain clearly how to send data from fragment to activity?
Keep a global reference to fragment instance and invoke refreshList from where you receive the response. public class YourActivity... { private Fragment fragmentInstance; void someMethodReceivedNewList(){ // where you receive new list in activity if(fragmentinstance!= null) fragmentinstance.
onAttach(Activity) called once the fragment is associated with its activity. onCreate(Bundle) called to do initial creation of the fragment. onCreateView(LayoutInflater, ViewGroup, Bundle) creates and returns the view hierarchy associated with the fragment.
Step 1 − Create a new project in Android Studio, go to File ⇉ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main. xml. Step 3 − Create two FragmentActivity and add the codes which are given below.
You should do something like this. First create an interface which will use to comunicate with your activity for example :
public interface OnViewSelected {
public void onViewSelected(int viewId);
}
and in your onAttach
do this :
OnViewSelected _mClickListener;
@Override
public void onAttach(Context context) {
super.onAttach(context);
try {
_mClickListener = (OnViewSelected) context;
} catch (ClassCastException e) {
throw new ClassCastException(context.toString() + " must implement onViewSelected");
}
}
In your Fragment implement OnClickListener
and in your onClick()
method do this :
@Override
public void onClick(View v) {
_mClickListener.onViewSelected(456);
}
After that in your Activity you have to implement the interface you created in your Fragment and it will ask you to add unimplemented methods and in your activity you will have function like this :
@Override
public void onViewSelected(int data) {
Log.d("","data : "+data); // this value will be 456.
}
That's all. : )
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With