Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

onAttach callback from fragment to activity

Tags:

android

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?

like image 386
user1526671 Avatar asked Jan 08 '13 11:01

user1526671


People also ask

How can we send callback 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.

What is onAttach in fragment?

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.

How pass data from fragment to activity Kotlin?

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.


1 Answers

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. : )

like image 85
hardartcore Avatar answered Oct 24 '22 19:10

hardartcore