Create Simple Fragment in Android Studio

Objective:
To create a simple fragment

Function:
Text View from both main layout and fragment can be view on same screen. The reason is to show that fragment can be view and run on top of the main layout.

IDE:
Android Studio 1.0.2

Source Code:
The project can be downloaded from here.

Result:



Explanation:
Code with commented with to explain further more.

Content of MainActivity.java file:

package com.example.osdevlab.simplefragmenttutorial;

import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;


public class MainActivity extends ActionBarActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main); //set to activity_main.xml

        /*way of adding fragment with java*/
        //FragmentOne is the class which inflate the fragment_one.xml and return the view
        FragmentOne myFragment = new FragmentOne();
        FragmentManager manager = getFragmentManager();
        FragmentTransaction transaction = manager.beginTransaction();
        //'container' is android id in activity_main.xml
        //add android:id="@+id/container" in activity_main.xml
        transaction.add(R.id.container, myFragment, "main_layout_container");
        transaction.commit();
    }
}


Content of FragmentOne.java file:
package com.example.osdevlab.simplefragmenttutorial;

import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

/**
 * Created by osdevlab on 12/29/14.
 */
public class FragmentOne extends Fragment {


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        // Inflate the layout with fragment_one.xml
        return inflater.inflate(R.layout.fragment_one, container, false);
    }


}

No comments:

Post a Comment