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 use Preference Activity in Android

Preference Activity is a base class mainly used for setting order of preferences of an user.It is mainly used for creating setting page of an user.In this example I am just showing how to set Preferences. First create an Activity MainActivity.java Here on clicking preference example button a page will be opened to set the preferences. On clicking the show values we can see the see the values that we have set. MainActivity.java import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Button btn = (Button) findViewById(R.id.btn_pref); Button btn1 = (Button) findViewById(R.id.btn_values); btn.setOnCli...

Get List of All Installed Apps

For getting the list of all apps installed in the device and to show it on a listview we can use the following code: MainActivity.java import java.util.ArrayList; import java.util.List; import android.content.Intent; import android.content.pm.ApplicationInfo; import android.content.pm.PackageManager; import android.os.Bundle; import android.support.v7.app.ActionBarActivity; import android.widget.ArrayAdapter; import android.widget.ListView; public class MainActivity extends ActionBarActivity { ArrayList results_sys_app = new ArrayList(); ArrayAdapter<applicationinfo>adapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); final Intent mainIntent = new Intent(Intent.ACTION_MAIN, null); mainIntent.addCategory(Intent.CATEGORY_LAUNCHER); final List<applicationinfo> pkgAppsList = this.getPackageManager().getInstalledApplications( PackageManager.GET_UNINSTALLED_PAC...

How to save contacts to the phone contacts in android

We can easily save the contacts to the phone contacts without having any database of own . The code is very simple. import android.app.Activity; import android.app.AlertDialog; import android.content.ComponentName; import android.content.ContentValues; import android.content.DialogInterface; import android.content.Intent; import android.database.Cursor; import android.net.Uri; import android.os.Bundle; import android.provider.Contacts; import android.provider.Contacts.People; import android.provider.ContactsContract; import android.provider.ContactsContract.CommonDataKinds.Phone; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.EditText; public class MainActivity extends Activity { protected static final int PICK_CONTACT = 0; EditText edt1,edt2; Button btn; String s1,s2; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activ...