Skip to main content

How to implement a fragment in Android

 We can call fragment as a sub activity. By using fragment navigation will more easier and in tabs layouts look cool.Let us see an example.....
Here we have 2 fragment class Details, and Detail2.
MainActivity.java

import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentTransaction;
import android.os.Bundle;

public class MainActivity extends Activity {

 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);
//Here we call the first fragment
  Fragment fragment = null;
  fragment = new Options();
  FragmentTransaction fragmentTransaction = getFragmentManager()
    .beginTransaction();

  fragmentTransaction.replace(R.id.frame1, fragment).commit();

 }

}

Options.java


import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.os.Bundle;

import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.TextView;

public class Options extends Fragment implements OnClickListener {
 View mRoot;
 TextView txt_andro, txt_ios;
 Fragment fragment = null;
 FragmentManager fragmentManager;
 FragmentTransaction fragmentTransaction;

 @Override
 public View onCreateView(LayoutInflater inflater, ViewGroup container,
   Bundle savedInstanceState) {
  // TODO Auto-generated method stub
  mRoot = inflater.inflate(R.layout.fragment1, null);
  txt_andro = (TextView) mRoot.findViewById(R.id.txt1);
  txt_ios = (TextView) mRoot.findViewById(R.id.txt2);
 

  txt_andro.setOnClickListener(this);
  txt_ios.setOnClickListener(this);
 
  fragmentManager = getFragmentManager();
  fragmentTransaction = fragmentManager.beginTransaction();
  // defaultly load the first page
  fragment = new Details();
  Bundle bundle = new Bundle();
  bundle.putString("name", "android");
  fragment.setArguments(bundle);
  fragmentTransaction = getFragmentManager().beginTransaction();

  fragmentTransaction.replace(R.id.frame2, fragment).commit();

  return mRoot;
 }

 @Override
 public void onClick(View v) {
  // TODO Auto-generated method stub

  switch (v.getId()) {
  case R.id.txt1:
   fragment = new Details();
   
   // to pass value from one fragment to other
   Bundle bundle = new Bundle();
   bundle.putSerializable("name", "android");
   fragment.setArguments(bundle);
   fragmentTransaction = getFragmentManager().beginTransaction();

   fragmentTransaction.replace(R.id.frame2, fragment).commit();
   break;
  case R.id.txt2:
   fragment = new Detail2();
   Bundle bundle1 = new Bundle();
   bundle1.putSerializable("name", "ios");
   fragment.setArguments(bundle1);
   fragmentTransaction = getFragmentManager().beginTransaction();

   fragmentTransaction.replace(R.id.frame2, fragment).commit();

   break;
  
  default:
   break;
  }

 }
}


Details.java

import java.util.ArrayList;

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

public class Details extends Fragment {
 View mRoot;
 TextView txt_description;
 String value;

 @Override
 public View onCreateView(LayoutInflater inflater, ViewGroup container,
   Bundle savedInstanceState) {
  // TODO Auto-generated method stub
  mRoot = inflater.inflate(R.layout.fragment2, null);
  txt_description = (TextView) mRoot.findViewById(R.id.textView1);
  if (getArguments() != null) {
   Bundle args = getArguments();
   value = args.getString("name");
   System.out.println(value);
   txt_description.setText(value);
  }

  
  return mRoot;
 }

}
Details2.java

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

public class Detail2 extends Fragment {
 View mRoot;
 TextView txt_description;
 String value;

 @Override
 public View onCreateView(LayoutInflater inflater, ViewGroup container,
   Bundle savedInstanceState) {
  // TODO Auto-generated method stub
  mRoot = inflater.inflate(R.layout.fragment3, null);
  txt_description = (TextView) mRoot.findViewById(R.id.textView1);
  if (getArguments() != null) {
   Bundle args = getArguments();
   value = args.getString("name");
   System.out.println(value);
   txt_description.setText(value);
  }

  
  return mRoot;
 }

}

activity_main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".FragmentExampleActivity" >
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="horizontal"
        android:layout_marginTop="10dp"
        android:layout_marginBottom="10dp" >

        <FrameLayout             android:id="@+id/frame1"             android:layout_width="0dip"             android:layout_height="match_parent"             android:layout_marginLeft="10dp"             android:layout_weight=".3"             android:padding="20dp"             android:background="#777777"              >         </FrameLayout>
        <FrameLayout             android:id="@+id/frame2"             android:layout_width="0dip"             android:layout_height="match_parent"             android:layout_marginLeft="10dp"             android:layout_marginRight="10dp"             android:layout_weight=".7"             android:paddingLeft="10dp"             android:paddingRight="10dp"                android:background="#777777">         </FrameLayout>     </LinearLayout>
</RelativeLayout>
fragment1.xml

?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >
    <RelativeLayout
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_marginBottom="50dp"
        android:layout_marginLeft="50dp"
        android:layout_marginTop="50dp"
        android:orientation="vertical" >
        <TextView
            android:id="@+id/txt1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="android"
            android:textColor="#FFFFFF"
            android:textSize="20dp" />
        <TextView
            android:id="@+id/txt2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_below="@+id/txt1"
            android:paddingTop="10dp"
            android:text="ios"
            android:textColor="#FFFFFF"
            android:textSize="20dp" />
    </RelativeLayout>
</RelativeLayout>
fragment2.xml


<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >
    <ImageView
        android:id="@+id/img1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:src="@drawable/ic_launcher"/>
    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:text="Large Text"
        android:layout_below="@+id/img1"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:textColor="#FFFFFF" />
</RelativeLayout>
fragment3.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >
    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:text="Large Text"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:textColor="#FFFFFF" />
</RelativeLayout>
While using fragment we can use

fragmentTransaction.replace(R.id.frame2, fragment).commit();
or
fragmentTransaction.add(R.id.frame2, fragment).commit();

But there is difference in both, if we use "replace" it means it replaces existing fragment and loads the next.If we use "add" it will add the new fragment to the older.So the one fragment will be added over the other.. Use of

fragmentTransaction.addToBackStack(str);
 If we use addToBackStack it means the fragment transaction ia added to the back stack.The transaction will be remained even after committing.

Comments

Popular posts from this blog

How to record and save a video in Android

Let's record a video :). Check the code snippet. First need to give necessary permissions. So add these permissions to AndroidManifest.xml   <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />   <uses-permission android:name="android.permission.RECORD_AUDIO" /> MainActivity.java import java.io.File; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Locale; import android.app.Activity; import android.content.Intent; import android.content.pm.PackageManager; import android.graphics.Color; import android.graphics.drawable.ColorDrawable; import android.net.Uri; import android.os.Bundle; import android.os.Environment; import android.provider.MediaStore; import android.util.Log; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.Toast; public class MainActivity extends Activity implements OnClickListener { Button btn_record; pu

How to create a flash light on Android

I always wonder the use of a flash light on a phone. This simple app is more useful than anything. So here is the code to build a flashlight app, MainActivity.java import android.app.Activity; import android.app.AlertDialog; import android.content.DialogInterface; import android.content.pm.PackageManager; import android.hardware.Camera; import android.hardware.Camera.Parameters; import android.media.MediaPlayer; import android.media.MediaPlayer.OnCompletionListener; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.ImageButton; public class MainActivity extends Activity { ImageButton btnSwitch; private Camera camera; private boolean isFlashOn; private boolean hasFlash; Parameters params; MediaPlayer mp; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // flash switch button