Passing Data between fragments in Android using Interface 1

Passing Data between fragments in Android using Interface

public class MainActivity extends ActionBarActivity implements DataPassListener{
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        if (findViewById(R.id.container) != null) {
            if (savedInstanceState != null) {
                return;
            }
            getFragmentManager().beginTransaction()
                    .add(R.id.container, new FragmentA()).commit();
        }
    }
    
    @Override
    public void passData(String data) {
        FragmentB fragmentB = new FragmentB ();
        Bundle args = new Bundle();
        args.putString(FragmentB.DATA_RECEIVE, data);
        fragmentB .setArguments(args);
        getFragmentManager().beginTransaction()
            .replace(R.id.container, fragmentB )
            .commit();
    }
}

Here is what the above code is Doing:
1. The MainActivity implements the DataPassListener interface.
2. The MainActivity class implements the passData() method of the DataPassListener interface.
3. The passData() method is called from the FragmentA class.
4. The passData() method creates an instance of the FragmentB class.
5. The passData() method passes the data to the FragmentB class using the setArguments() method.
6. The passData() method replaces the FragmentA class with the FragmentB class.

Similar Posts