Introduce fragment from activity in android

Concept of the fragment is new ‘quantum leap’ in Android programming. But before you start to run, you must learn how to walk first. So, we will start to introduce fragment from activity. We will remake our greatest common divisor GCD application in the sense that we will transfer interface from Activity to fragment. Open your project, go to

app→java→cirvirlab.gcd then right click and then New→Fragment→Fragment(Blank)

fragment-from-activity

Then give some name to your new fragment.

New-fragment-name

After new fragment class is created, as well as corresponding XML, go to XML of your main activity and copy all.

Copy-all-content-of-activity-main-xml

And replace existing content of your new fragment_gcd.xml by pasting copied content.

Now we return to activity_main.xml and remove all visual components there, replacing them by fragment. It looks like this:

<fragment

android:layout_width=”wrap_content”

android:layout_height=”wrap_content”

android:name=”cirvirlab.gcd.GCDFragment”>

</fragment>

Fragment-layout-width-hight-name-added

Next thing to do is to move code from MainActivity to GCDFragment. First delete unnecessary code

Delete-Unnecessary-code-inFragment-Java-class

Delete some more code.

Delete-Unnecessary-code-inFragment-Java-class02

And some more

Delete-Unnecessary-code-inFragment-Java-class03

So code that remains is:

Remaining-code-in-Fragment-java-class

Now, paste widget declarations from main activity code to fragment code.

Declare-Widgets-From-Main-Activity

In public View onCreateView method change

return inflater.inflate(R.layout.fragment_gcd, container, false);
to
View view = inflater.inflate(R.layout.fragment_gcd, container, false);

And cut declaration of the widgets from the MainActivity class, paste them and add view in front. Then return view.

Vew-in-front-of-the-code

In main activity cut onClick method

Cut-onClick-Method

And paste it in fragment class.

Paste-onClick-Method

In order to make things work, return to activity_main.xml and put the id of the fragment. Then go fragment_gcd.xml and cut declaration of onClick method.

Cut-android-onClick-calculateGCD

Go to GCDFragment and declare button

Declare-Button-btnGCD

In onCreateView define new button:

btnGCD = (Button)view.findViewById(R.id.button);

Define-Button-btnGCD

Attach onClickListener

btnGCD.setOnClickListener(new View.OnClickListener(){

public void onClick(View view1)

{

}

});

Code of this onclick method is

btnGCD.setOnClickListener(new View.OnClickListener(){

public void onClick(View view1)

{

calculateGCD(view1);

}

});

See on figure bellow.

calculateGCD-view1-code

External links:

Introduce fragment from activity in android on developer
Introduce fragment from activity in android on Stackoverflow

Posted in android Tagged with: ,

Leave a Reply

Your email address will not be published. Required fields are marked *

*