Thursday, 27 July 2017

Tutorial How to move from Activity to Fragment and Fragment to Activity

For those who learning android programming for the first time, they will learn about android components like Java Class, XML, Activity, Fragment, Adapter, etc.

After that the next step is learn how to move from one Activity to another Activity using Intent. After learn about Activity, that they will learn about how to move from Activity to Fragment, and the Fragment to Activity

Move From Activity To Fragment

On this part, i will show you two ways how to move from Activity to Fragment:

1. Using Activity For Place a Fragment

We call the fragment in Activity's layout. So when you try to access a Fragment, just call the Activity where you set the fragment using Intent.

Here is the example :

Create a XML file name it as activity_main.xml

Layout activity_main.xml will used on class MainActivity. Code for class looks like the follows :

Well, above is a class that we used as the first page when application is opened

Create a class Fragment and name it as, Here is the code :

Next create layout for Fragment NameFragment name it as fragment_name.xml, here is the code :

OK, class Fragment already done. So how can we call Fragment NameFragment from MainActivity?

Create a new layout name it as activity_for_fragment_name.xml

Take a look at above code, inside tag there is an attribute class, that contains class Fragment. From where the class com.putuguna.fragmenttoactivity.NameFragment? that is the name of class Fragment that we create before, that is NameFragment.

com.putuguna.fragmenttoactivity.NameFragment contains name of package project and name of class.
com.putuguna.fragmenttoactivity : name of package project that we created
NameFragment : name of class Fragment that we created

Then create a java class for Activity NameFragment, name it as, the code is looks like the follows :

As we can see there is not special initialize code inside class MainActivity, it just initialize of its layout. But when this class is loaded, by using attribute class inside tagline fragment, then automatically its fragment will loaded

Calling Fragment NameFragment from MainActivity, you can do it look like the following code :

The part of the code above available on MainActivity, inside button onClick

2.  Without using Class Activity

If you create fragment without create its Activity, simple do like the following code :

Move from Fragment To Activity

If you try access an Activity from a Fragment, simply like the following code :

Yang perlu diperhatikan adalah :

.... new Intent(getActivity(), .....), getActivity() as Activity of Fragment, because on Intent's constructor required Activity and destination class , so we use getActivity() to take fragment's activity.
And also before you do startActivity(), first write getActivity() then startActivity().
That's all. Sorry for worst english. Thank you.