Category Archives: Fragments

How to handle configuration change in an activity using Fragments in android?

Here is a simple example in which we will save or retain the state of the progress using fragments.

Note : We have handle a configuration by another way – by ignoring the change i.e using this property in the activity tag
android:configChanges=””
By using this android ignores the configuration change and will never try to create a new instance of the activity.
But Google discourages this practice.

Handling configuration changes requires you to take many additional steps to ensure that each and every string, layout, drawable, dimension, etc. remains in sync with the device’s current configuration, and if you aren’t careful, you’re application can easily have a whole series of resource-specific bugs as a result.

Another reason why Google discourages its use is because many developers incorrectly assume that setting android:configChanges=”orientation” (for example) will magically protect their application from unpredictable scenarios in which the underlying Activity will be destroyed and recreated. This is not the case. Configuration changes can occur for a number of reasons—not just screen orientation changes. Inserting your device into a display dock, changing the default language, and modifying the device’s default font scaling factor are just three examples of events that can trigger a device configuration change, all of which signal the system to destroy and recreate all currently running Activitys the next time they are resumed. As a result, setting the android:configChanges attribute is generally not good practice.

retain state

retain state

Let’s go to the code and see how it is done.

Now we will see how to do that.

At first I will show you the layout which simply contains a textview that show the progress.

<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=".MainActivity" >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:padding="10dp"
        android:layout_alignParentTop="true"
        android:text="Handling Runtime configuration changes by saving state using Fragments"
        android:textColor="@android:color/black"
        android:textSize="20sp" />

    <FrameLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true" >

        <TextView
            android:id="@+id/tv_pro"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerHorizontal="true"
            android:layout_centerVertical="true"
            android:textColor="@android:color/holo_blue_bright"
            android:textSize="40sp" />
    </FrameLayout>

</RelativeLayout>

Now we will see the code for the activity.

package com.example.retaininstanceusingfragmentsexample;

import android.app.Activity;
import android.app.FragmentManager;
import android.os.Bundle;
import android.widget.TextView;

public class MainActivity extends Activity implements
		TaskFragment.TaskCallbacks {

	private TaskFragment mTaskFragment;
	TextView tvPro = null;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		tvPro = (TextView) findViewById(R.id.tv_pro);

		FragmentManager fm = getFragmentManager();
		mTaskFragment = (TaskFragment) fm.findFragmentByTag("task");

		// If the Fragment is not null, then it is currently being
		// retained when a configuration change occurs.
		if (mTaskFragment == null) {
			mTaskFragment = new TaskFragment();
			fm.beginTransaction().add(mTaskFragment, "task").commit();
		}

		// TODO: initialize views, restore saved state, etc.
	}

	@Override
	public void onPreExecute() {
	}

	@Override
	public void onProgressUpdate(int percent) {
		tvPro.setText(percent + "%");
	}

	@Override
	public void onCancelled() {
	}

	@Override
	public void onPostExecute() {
	}
}

Now the Fragments that handles the retained state.

package com.example.retaininstanceusingfragmentsexample;

import android.app.Activity;
import android.app.Fragment;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.SystemClock;

/**
 * This Fragment manages a single background task and retains itself across
 * configuration changes.
 */
public class TaskFragment extends Fragment {

	/**
	 * Callback interface through which the fragment will report the task's
	 * progress and results back to the Activity.
	 */
	static interface TaskCallbacks {
		void onPreExecute();

		void onProgressUpdate(int percent);

		void onCancelled();

		void onPostExecute();
	}

	private TaskCallbacks mCallbacks;
	private DummyTask mTask;

	/**
	 * Hold a reference to the parent Activity so we can report the task's
	 * current progress and results. The Android framework will pass us a
	 * reference to the newly created Activity after each configuration change.
	 */
	@Override
	public void onAttach(Activity activity) {
		super.onAttach(activity);
		mCallbacks = (TaskCallbacks) activity;
	}

	/**
	 * This method will only be called once when the retained Fragment is first
	 * created.
	 */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		// Retain this fragment across configuration changes.
		setRetainInstance(true);

		// Create and execute the background task.
		mTask = new DummyTask();
		mTask.execute();
	}

	/**
	 * Set the callback to null so we don't accidentally leak the Activity
	 * instance.
	 */
	@Override
	public void onDetach() {
		super.onDetach();
		mCallbacks = null;
	}

	/**
	 * A dummy task that performs some (dumb) background work and update the UI
	 */
	private class DummyTask extends AsyncTask<Void, Integer, Void> {

		@Override
		protected void onPreExecute() {
			if (mCallbacks != null) {
				mCallbacks.onPreExecute();
			}
		}

		/**
		 * Note that we do NOT call the callback object's methods directly from
		 * the background thread, as this could result in a race condition.
		 */
		@Override
		protected Void doInBackground(Void... ignore) {
			for (int i = 0; !isCancelled() && i < 100; i++) {
				SystemClock.sleep(500);
				// call to onProgressUpdate
				publishProgress(i);
			}
			return null;
		}

		@Override
		protected void onProgressUpdate(Integer... percent) {
			if (mCallbacks != null) {
				mCallbacks.onProgressUpdate(percent[0]);
			}
		}

		@Override
		protected void onCancelled() {
			if (mCallbacks != null) {
				mCallbacks.onCancelled();
			}
		}

		@Override
		protected void onPostExecute(Void ignore) {
			if (mCallbacks != null) {
				mCallbacks.onPostExecute();
			}
		}
	}
}

After running this application, try to rotate the device and see how the fragment retains the state of the progress.

You can download the complete source code of this post from here.

FlipCard animation using Fragments in Android.

Hello all

I am back with fragments again. I know you have seen a lot of posts on fragments and fragment animation.

This one will be another useful post for you.

This post helps you to show a FlipCard animation using Fragments.

Let us see how can we do this.

At first I will show the activity that I am using to create Animation which contain two fragments for Front and Back Page.

CardFlipActivity.java


package com.example.cardflipanimation;

import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentManager;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.NavUtils;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;

public class CardFlipActivity extends Activity implements
		FragmentManager.OnBackStackChangedListener {
	/**
	 * A handler object, used for deferring UI operations.
	 */
	private Handler mHandler = new Handler();

	/**
	 * Whether or not we're showing the back of the card (otherwise showing the
	 * front).
	 */
	private boolean mShowingBack = false;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_card_flip);

		if (savedInstanceState == null) {
			// If there is no saved instance state, add a fragment representing
			// the
			// front of the card to this activity. If there is saved instance
			// state,
			// this fragment will have already been added to the activity.
			getFragmentManager().beginTransaction()
					.add(R.id.container, new CardFrontFragment()).commit();
		} else {
			mShowingBack = (getFragmentManager().getBackStackEntryCount() > 0);
		}

		// Monitor back stack changes to ensure the action bar shows the
		// appropriate
		// button (either "photo" or "info").
		getFragmentManager().addOnBackStackChangedListener(this);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		super.onCreateOptionsMenu(menu);

		// Add either a "photo" or "finish" button to the action bar, depending
		// on which page
		// is currently selected.
		MenuItem item = menu.add(Menu.NONE, R.id.action_flip, Menu.NONE,
				mShowingBack ? R.string.action_photo : R.string.action_info);
		item.setIcon(mShowingBack ? R.drawable.ic_action_photo
				: R.drawable.ic_action_info);
		item.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case android.R.id.home:
			// Navigate "up" the demo structure to the launchpad activity.
			// See http://developer.android.com/design/patterns/navigation.html
			// for more.
			NavUtils.navigateUpTo(this,
					new Intent(this, CardFlipActivity.class));
			return true;

		case R.id.action_flip:
			flipCard();
			return true;
		}

		return super.onOptionsItemSelected(item);
	}

	private void flipCard() {
		if (mShowingBack) {
			getFragmentManager().popBackStack();
			return;
		}

		// Flip to the back.

		mShowingBack = true;

		// Create and commit a new fragment transaction that adds the fragment
		// for the back of
		// the card, uses custom animations, and is part of the fragment
		// manager's back stack.

		getFragmentManager().beginTransaction()

		// Replace the default fragment animations with animator resources
		// representing
		// rotations when switching to the back of the card, as well as animator
		// resources representing rotations when flipping back to the front
		// (e.g. when
		// the system Back button is pressed).
				.setCustomAnimations(R.animator.card_flip_right_in,
						R.animator.card_flip_right_out,
						R.animator.card_flip_left_in,
						R.animator.card_flip_left_out)

				// Replace any fragments currently in the container view with a
				// fragment
				// representing the next page (indicated by the just-incremented
				// currentPage
				// variable).
				.replace(R.id.container, new CardBackFragment())

				// Add this transaction to the back stack, allowing users to
				// press Back
				// to get to the front of the card.
				.addToBackStack(null)

				// Commit the transaction.
				.commit();

		// Defer an invalidation of the options menu (on modern devices, the
		// action bar). This
		// can't be done immediately because the transaction may not yet be
		// committed. Commits
		// are asynchronous in that they are posted to the main thread's message
		// loop.
		mHandler.post(new Runnable() {
			@Override
			public void run() {
				invalidateOptionsMenu();
			}
		});
	}

	@Override
	public void onBackStackChanged() {
		mShowingBack = (getFragmentManager().getBackStackEntryCount() > 0);

		// When the back stack changes, invalidate the options menu (action
		// bar).
		invalidateOptionsMenu();
	}

	/**
	 * A fragment representing the front of the card.
	 */
	public static class CardFrontFragment extends Fragment {
		public CardFrontFragment() {
		}

		@Override
		public View onCreateView(LayoutInflater inflater, ViewGroup container,
				Bundle savedInstanceState) {
			return inflater.inflate(R.layout.fragment_card_front, container,
					false);
		}
	}

	/**
	 * A fragment representing the back of the card.
	 */
	public static class CardBackFragment extends Fragment {
		public CardBackFragment() {
		}

		@Override
		public View onCreateView(LayoutInflater inflater, ViewGroup container,
				Bundle savedInstanceState) {
			return inflater.inflate(R.layout.fragment_card_back, container,
					false);
		}
	}
}

Now the animations.
For that you have to create 4 xml animation files in the res/animator folder.

card_flip_left_in.xml
card_flip_left_out.xml
card_flip_right_in.xml
card_flip_right_out.xml

I will be listing these files in this order.

<set xmlns:android="http://schemas.android.com/apk/res/android">
    <!-- Before rotating, immediately set the alpha to 0. -->
    <objectAnimator
        android:valueFrom="1.0"
        android:valueTo="0.0"
        android:propertyName="alpha"
        android:duration="0" />

    <!-- Rotate. -->
    <objectAnimator
        android:valueFrom="-180"
        android:valueTo="0"
        android:propertyName="rotationY"
        android:interpolator="@android:interpolator/accelerate_decelerate"
        android:duration="@integer/card_flip_time_full" />

    <!-- Half-way through the rotation (see startOffset), set the alpha to 1. -->
    <objectAnimator
        android:valueFrom="0.0"
        android:valueTo="1.0"
        android:propertyName="alpha"
        android:startOffset="@integer/card_flip_time_half"
        android:duration="1" />
</set>

<set xmlns:android="http://schemas.android.com/apk/res/android">
    <!-- Rotate. -->
    <objectAnimator android:valueFrom="0"
        android:valueTo="180"
        android:propertyName="rotationY"
        android:interpolator="@android:interpolator/accelerate_decelerate"
        android:duration="@integer/card_flip_time_full"></objectAnimator>

    <!-- Half-way through the rotation (see startOffset), set the alpha to 0. -->
    <objectAnimator android:valueFrom="1.0"
        android:valueTo="0.0"
        android:propertyName="alpha"
        android:startOffset="@integer/card_flip_time_half"
        android:duration="1"></objectAnimator>
</set>
<set xmlns:android="http://schemas.android.com/apk/res/android">
    <!-- Before rotating, immediately set the alpha to 0. -->
    <objectAnimator
        android:valueFrom="1.0"
        android:valueTo="0.0"
        android:propertyName="alpha"
        android:duration="0" />

    <!-- Rotate. -->
    <objectAnimator
        android:valueFrom="180"
        android:valueTo="0"
        android:propertyName="rotationY"
        android:interpolator="@android:interpolator/accelerate_decelerate"
        android:duration="@integer/card_flip_time_full" />

    <!-- Half-way through the rotation (see startOffset), set the alpha to 1. -->
    <objectAnimator
        android:valueFrom="0.0"
        android:valueTo="1.0"
        android:propertyName="alpha"
        android:startOffset="@integer/card_flip_time_half"
        android:duration="1" />
</set>

<set xmlns:android="http://schemas.android.com/apk/res/android">
    <!-- Rotate. -->
    <objectAnimator
        android:valueFrom="0"
        android:valueTo="-180"
        android:propertyName="rotationY"
        android:interpolator="@android:interpolator/accelerate_decelerate"
        android:duration="@integer/card_flip_time_full" />

    <!-- Half-way through the rotation (see startOffset), set the alpha to 0. -->
    <objectAnimator
        android:valueFrom="1.0"
        android:valueTo="0.0"
        android:propertyName="alpha"
        android:startOffset="@integer/card_flip_time_half"
        android:duration="1" />
</set>

Inside the drawable folder put these images.

ic_action_info.png
ic_action_photo.png
image1.png

Put these inside the ids.xml folder inside the res/values folder.

    <item type="id" name="action_next" />
    <item type="id" name="action_flip" />

strings.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>

    <string name="app_name">CardFlipAnimation</string>
    <string name="hello_world">Hello world!</string>
    <string name="menu_settings">Settings</string>
    <string name="action_info">Photo info</string>
    <string name="action_photo">View photo</string>

</resources>

And also integers.xml

<resources>
    <integer name="card_flip_time_full">300</integer>
    <integer name="card_flip_time_half">150</integer>
</resources>

Download the complete android source code from here.

How to get a return value from a DialogFragment? or Using DialogFragments in android.

Hello all……

This post examples how to get an edittext value from a dialog fragment.
You can use the same method to get a button click from a dialog or events like that.

Dialog Fragment

You can click on the download link to get the source code.

At first we will create a layout for the Dialog Fragment.
The layout contains only an editext. We are getting this edittext value from the fragment to the activity when the “DONE” button is clicked after inputting text.

frag_edit_name.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/edit_name"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="center"
    android:layout_margin="10dp"
    android:orientation="vertical" >

    <TextView
        android:id="@+id/lbl_your_name"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
         android:layout_margin="10dp"
        android:text="Your name" />

    <EditText
        android:id="@+id/txt_your_name"
        android:layout_width="match_parent"
        android:layout_height="fill_parent"
        android:hint="Type your name"
        android:imeOptions="actionDone"
        android:inputType="text" />

</LinearLayout>

Next we will write the class for the DialogFragment.

MyDialogFragment is my class name for the DialogFragment.

MyDialogFragment.java

package com.example.dialogfragmentsexxample;

import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;

public class MyDialogFragment extends DialogFragment implements
		OnEditorActionListener {

	public interface EditNameDialogListener {
		void onFinishEditDialog(String inputText);
	}

	private EditText mEditText;

	public MyDialogFragment() {
		// Empty constructor required for DialogFragment
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.frag_edit_name, container);
		mEditText = (EditText) view.findViewById(R.id.txt_your_name);
		getDialog().setTitle("Dialog Fragment Example");

		// Show soft keyboard automatically
		mEditText.requestFocus();
		mEditText.setOnEditorActionListener(this);

		return view;
	}

	@Override
	public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
		if (EditorInfo.IME_ACTION_DONE == actionId) {
			// Return input text to activity
			EditNameDialogListener activity = (EditNameDialogListener) getActivity();
			activity.onFinishEditDialog(mEditText.getText().toString());
			this.dismiss();
			return true;
		}
		return false;
	}
}

OK Now our fragment is complete.
Here we use interface to get value from the editext in the DialogFragment.

This is the interface which has only one method

onFinishEditDialog

Now we implement this interface in the activity and call the method “onFinishEditDialog” from the dialog after inputting the text.
This is the line that calls this function from the dialogfragment.

activity.onFinishEditDialog(mEditText.getText().toString());

This is the activity class.

MainActivity.java

package com.example.dialogfragmentsexxample;

import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.widget.TextView;

import com.example.dialogfragmentsexxample.MyDialogFragment.EditNameDialogListener;

public class MainActivity extends FragmentActivity implements
		EditNameDialogListener {

	TextView txt = null;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		txt = new TextView(this);
		txt.setText("Nothing received from Dialog Fragment");
		txt.setTextSize(30);
		setContentView(txt);
		showEditDialog();
	}

	private void showEditDialog() {
		FragmentManager fm = getSupportFragmentManager();
		MyDialogFragment editNameDialog = new MyDialogFragment();
		editNameDialog.show(fm, "fragment_edit_name");
	}

	@Override
	public void onFinishEditDialog(String inputText) {
		txt.setText("Input value from DialogFragment " + inputText);
	}
}

Please leave your valuable comments if you found this post useful.

You can download the complete source code for the above post from here.

Use of custom animations in a FragmentTransaction when pushing and popping a stack. or How to apply animations in Fragments when pushing on to a stack?

Hello all

We have seen many examples of how to use fragments in android.
You can search coderzheaven for all types of transactions using Fragments.
Today in this post we will see how we can apply animations to Fragments when pushing on to a stack.

This is fairly a long example. I will try to explain with code one by one,
You can click on the download link to get the source code.

Fragment

Fragment

Fragment

Here we start.

At first we will see the layout used in the Fragment.

hello_world.xml

<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/text"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center_vertical|center_horizontal"
    android:text="@string/hello_world"
    android:textAppearance="?android:attr/textAppearanceMedium" />

Now the layout for the activity.
fragment_stack.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center_horizontal"
    android:orientation="vertical"
    android:padding="4dip" >

    <FrameLayout
        android:id="@+id/simple_fragment"
        android:layout_width="match_parent"
        android:layout_height="0px"
        android:layout_weight="1" >
    </FrameLayout>

    <Button
        android:id="@+id/new_fragment"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight="0"
        android:text="@string/new_fragment" >

        <requestFocus />
    </Button>

</LinearLayout>

Now the xml for the animations in the Fragment.
First create a folder inside res folder called “animator” and create four xml files inside it.

fragment_slide_left_enter.xml
fragment_slide_left_exit.xml
fragment_slide_right_enter.xml
fragment_slide_right_exit.xml

fragment_slide_left_enter.xml

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
    <objectAnimator
        android:interpolator="@android:interpolator/decelerate_quint"
        android:valueFrom="100dp" android:valueTo="0dp"
        android:valueType="floatType"
        android:propertyName="translationX"
        android:duration="@android:integer/config_mediumAnimTime" />
    <objectAnimator
        android:interpolator="@android:interpolator/decelerate_quint"
        android:valueFrom="0.0" android:valueTo="1.0"
        android:valueType="floatType"
        android:propertyName="alpha"
        android:duration="@android:integer/config_mediumAnimTime" />
</set>

fragment_slide_left_exit.xml

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
    <objectAnimator
        android:interpolator="@android:interpolator/decelerate_quint"
        android:valueFrom="0dp" android:valueTo="-100dp"
        android:valueType="floatType"
        android:propertyName="translationX"
        android:duration="@android:integer/config_mediumAnimTime" />
    <objectAnimator
        android:interpolator="@android:interpolator/decelerate_quint"
        android:valueFrom="1.0" android:valueTo="0.0"
        android:valueType="floatType"
        android:propertyName="alpha"
        android:duration="@android:integer/config_mediumAnimTime" />
</set>

fragment_slide_right_enter.xml

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
    <objectAnimator
        android:interpolator="@android:interpolator/decelerate_quint"
        android:valueFrom="-100dp" android:valueTo="0dp"
        android:valueType="floatType"
        android:propertyName="translationX"
        android:duration="@android:integer/config_mediumAnimTime" />
    <objectAnimator
        android:interpolator="@android:interpolator/decelerate_quint"
        android:valueFrom="0.0" android:valueTo="1.0"
        android:valueType="floatType"
        android:propertyName="alpha"
        android:duration="@android:integer/config_mediumAnimTime" />
</set>

fragment_slide_right_exit.xml

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
    <objectAnimator
        android:interpolator="@android:interpolator/decelerate_quint"
        android:valueFrom="0dp" android:valueTo="100dp"
        android:valueType="floatType"
        android:propertyName="translationX"
        android:duration="@android:integer/config_mediumAnimTime" />
    <objectAnimator
        android:interpolator="@android:interpolator/decelerate_quint"
        android:valueFrom="1.0" android:valueTo="0.0"
        android:valueType="floatType"
        android:propertyName="alpha"
        android:duration="@android:integer/config_mediumAnimTime" />
</set>

Now the activity that do all the transactions in the Fragment.

FragmentCustomAnimations.java

package com.example.fragmentcustomanimations;

import android.app.Activity;
import android.app.Fragment;
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.Button;
import android.widget.TextView;

/**
 * Demonstrates the use of custom animations in a FragmentTransaction when
 * pushing and popping a stack.
 */
public class FragmentCustomAnimations extends Activity {
    int mStackLevel = 1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.fragment_stack);

        // Watch for button clicks.
        Button button = (Button)findViewById(R.id.new_fragment);
        button.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                addFragmentToStack();
            }
        });

        if (savedInstanceState == null) {
            // Do first time initialization -- add initial fragment.
            Fragment newFragment = CountingFragment.newInstance(mStackLevel);
            FragmentTransaction ft = getFragmentManager().beginTransaction();
            ft.add(R.id.simple_fragment, newFragment).commit();
        } else {
            mStackLevel = savedInstanceState.getInt("level");
        }
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putInt("level", mStackLevel);
    }


    void addFragmentToStack() {
        mStackLevel++;

        // Instantiate a new fragment.
        Fragment newFragment = CountingFragment.newInstance(mStackLevel);

        // Add the fragment to the activity, pushing this transaction
        // on to the back stack.
        FragmentTransaction ft = getFragmentManager().beginTransaction();
        ft.setCustomAnimations(R.animator.fragment_slide_left_enter,
                R.animator.fragment_slide_left_exit,
                R.animator.fragment_slide_right_enter,
                R.animator.fragment_slide_right_exit);
        ft.replace(R.id.simple_fragment, newFragment);
        ft.addToBackStack(null);
        ft.commit();
    }

    public static class CountingFragment extends Fragment {
        int mNum;
        /**
         * Create a new instance of CountingFragment, providing "num"
         * as an argument.
         */
        static CountingFragment newInstance(int num) {
            CountingFragment f = new CountingFragment();

            // Supply num input as an argument.
            Bundle args = new Bundle();
            args.putInt("num", num);
            f.setArguments(args);

            return f;
        }

        /**
         * When creating, retrieve this instance's number from its arguments.
         */
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            mNum = getArguments() != null ? getArguments().getInt("num") : 1;
        }

        /**
         * The Fragment's UI is just a simple text view showing its
         * instance number.
         */
        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                Bundle savedInstanceState) {
            View v = inflater.inflate(R.layout.hello_world, container, false);
            View tv = v.findViewById(R.id.text);
            ((TextView)tv).setText("Fragment #" + mNum);
            tv.setBackgroundDrawable(getResources().getDrawable(android.R.drawable.gallery_thumb));  
            return v;
        }
    }

}

You can download the complete source code from here.

How to display a context menu from a fragment?

Hello all

I think you all know about the context menu in android. It appears as a popup when you long press something. Fragment also provides some methods for registering with the contextmenu and showing it.

Fragment Context Menu

Fragment Context Menu

Let’s see how we can do it.
You can click on the download links to download the source code.

At first we will look at the simple layout for demonstrating this example.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:padding="8dp">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:text="@string/fragment_context_menu_msg" />

    <Button android:id="@+id/long_press"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:text="Long Press Me">
        <requestFocus />
    </Button>
    
</LinearLayout>

Now create a folder named “menu” inside the res folder inside your project.
And create an xml file named “my_menu.xml” inside this folder and copy this code into it.

<menu xmlns:android="http://schemas.android.com/apk/res/android">

    <item android:id="@+id/invisible_item"
        android:visible="false"
        android:alphabeticShortcut="i"
        android:title="Invisible item" />

    <item android:id="@+id/a_item"
        android:alphabeticShortcut="a"
        android:title="Alvin" />

    <item android:id="@+id/b_item"
        android:alphabeticShortcut="b"
        android:title="Bart" />

    <item android:id="@+id/c_item"
        android:alphabeticShortcut="c"
        android:title="Chris" />

    <item android:id="@+id/d_item"
        android:alphabeticShortcut="d"
        android:title="David" />

    <item android:id="@+id/e_item"
        android:alphabeticShortcut="e"
        android:title="Eric" />

    <item android:id="@+id/f_item"
        android:alphabeticShortcut="f"
        android:title="Frank" />

    <item android:id="@+id/g_item"
        android:alphabeticShortcut="g"
        android:title="Gary" />

    <item android:id="@+id/h_item"
        android:alphabeticShortcut="h"
        android:title="Henry" />

    <item android:id="@+id/excl_item"
        android:alphabeticShortcut="!"
        android:title="Exclamation" />

</menu>

I am using only two of the items from the above XML for showing the context menu.
Now we will go to the java code. My Activity is named FragmentContextMenu.java which looks like this.

package com.coderzheaven.fragmentcontextmenu;

import android.app.Activity;
import android.app.Fragment;
import android.os.Bundle;
import android.util.Log;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;

/**
 * Demonstration of displaying a context menu from a fragment.
 */
public class FragmentContextMenu extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // Create the list fragment and add it as our sole content.
        ContextMenuFragment content = new ContextMenuFragment();
        getFragmentManager().beginTransaction().add(android.R.id.content, content).commit();
    }

    public static class ContextMenuFragment extends Fragment {

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                Bundle savedInstanceState) {
            View root = inflater.inflate(R.layout.fragment_context_menu, container, false);
            registerForContextMenu(root.findViewById(R.id.long_press));
            return root;
        }

        @Override
        public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
            super.onCreateContextMenu(menu, v, menuInfo);
            menu.add(Menu.NONE, R.id.a_item, Menu.NONE, "Menu A");
            menu.add(Menu.NONE, R.id.b_item, Menu.NONE, "Menu B");
        }

        @Override
        public boolean onContextItemSelected(MenuItem item) {
            switch (item.getItemId()) {
                case R.id.a_item:
                    Log.i("ContextMenu", "Item 1a was chosen");
                    return true;
                case R.id.b_item:
                    Log.i("ContextMenu", "Item 1b was chosen");
                    return true;
            }
            return super.onContextItemSelected(item);
        }
    }
}

And That’s all done. Now you can run the project and see the result.

You can download the complete source code from here.

How to initialize a Fragements with attributes as a Bundle at runtime and from attributes in a layout?

This post Demonstrates a fragment that can be configured through both Bundle arguments
and layout attributes.

Fragments

You can click on the links to download the source code.

Here there are two fragments in the layout, one is directly in the layout and the other is created dynamically with arguments at runtime.
Here is how we do it.
At first I will show you layout that contains the fragments.
fragment_arguments.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center_horizontal"
    android:orientation="vertical"
    android:padding="4dip" >

    <TextView
        android:id="@+id/text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_vertical|center_horizontal"
        android:layout_weight="0"
        android:gravity="top|center_horizontal"
        android:padding="4dip"
        android:text="@string/fragment_arguments_msg"
        android:textAppearance="?android:attr/textAppearanceMedium" />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:padding="4dip" >

        <fragment
            android:id="@+id/embedded"
            android:layout_width="0px"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            class="com.example.argumentsfragment.FragmentArguments$MyFragment"
            android:label="@string/fragment_arguments_embedded" />

        <FrameLayout
            android:id="@+id/created"
            android:layout_width="0px"
            android:layout_height="wrap_content"
            android:layout_weight="1" />
    </LinearLayout>

</LinearLayout>

Now the layout for each fragment.
hello_world.xml

<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/text"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center_vertical|center_horizontal"
    android:text="@string/hello_world"
    android:textAppearance="?android:attr/textAppearanceMedium" />

OK layouts are now complete.

Now the activity that does the thing that we want to do.
FragmentArguments.java

package com.example.argumentsfragment;

import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentTransaction;
import android.content.res.TypedArray;
import android.os.Bundle;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

/**
 * Demonstrates a fragment that can be configured through both Bundle arguments
 * and layout attributes.
 */
public class FragmentArguments extends Activity {

    @Override protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.fragment_arguments);

        if (savedInstanceState == null) {
            // First-time init; create fragment to embed in activity.
            FragmentTransaction ft = getFragmentManager().beginTransaction();
            Fragment newFragment = MyFragment.newInstance("From Arguments");
            ft.add(R.id.created, newFragment);
            ft.commit();
        }
    }



    public static class MyFragment extends Fragment {
        CharSequence mLabel;

        /**
         * Create a new instance of MyFragment that will be initialized
         * with the given arguments.
         */
        static MyFragment newInstance(CharSequence label) {
        	System.out.println("newInstance");
            MyFragment f = new MyFragment();
            Bundle b = new Bundle();
            b.putCharSequence("label", label);
            f.setArguments(b);
            return f;
        }

        /**
         * Parse attributes during inflation from a view hierarchy into the
         * arguments we handle.
         */
        @Override public void onInflate(Activity activity, AttributeSet attrs,
                Bundle savedInstanceState) {
        	System.out.println("onInflate");
            super.onInflate(activity, attrs, savedInstanceState);

            TypedArray a = activity.obtainStyledAttributes(attrs,
                    R.styleable.FragmentArguments);
            mLabel = a.getText(R.styleable.FragmentArguments_android_label);
            a.recycle();
        }

        /**
         * During creation, if arguments have been supplied to the fragment
         * then parse those out.
         */
        @Override public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            System.out.println("onCreate");
            Bundle args = getArguments();
            if (args != null) {
                mLabel = args.getCharSequence("label", mLabel);
            }
        }

        /**
         * Create the view for this fragment, using the arguments given to it.
         */
        @Override public View onCreateView(LayoutInflater inflater, ViewGroup container,
                Bundle savedInstanceState) {
        	System.out.println("onCreateView");
            View v = inflater.inflate(R.layout.hello_world, container, false);
            View tv = v.findViewById(R.id.text);
            ((TextView)tv).setText(mLabel != null ? mLabel : "(no label)");
            tv.setBackgroundDrawable(getResources().getDrawable(android.R.drawable.gallery_thumb));
            return v;
        }
    }

}

Now create a file named “attr.xml” inside the res/values folder and copy this code into it.
It contains the styelable attribute.

<?xml version="1.0" encoding="utf-8"?>
<resources>

    <declare-styleable name="FragmentArguments">
        <attr name="android:label" />
    </declare-styleable>

</resources>

and copy these code to the strings.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>

    <string name="app_name">ArgumentsFragment</string>
    <string name="hello_world">Hello world!</string>
    <string name="menu_settings">Settings</string>
    <string name="fragment_arguments_msg">Demonstrates a fragment that takes arguments
        as a Bundle at runtime (on the right) or from attributes in a layout (on the left).</string>
    <string name="fragment_arguments_embedded">From Attributes</string>

</resources>

All code is now complete. Go on and run the project.

You can download the complete source code from here.

How to hide and show a Fragment with animation in Android? and How to retain a state in a Fragment in Android?

Hello everyone

This posts helps you to hide and show a fragment with animation (without XML files animation). And also it shows how to retain a saved state(for eg: a value in a textview).

A little about Fragments
A Fragments is an independent component which can be connected to an activity. A Fragment typically defines a part of a user interface but it is possible to define headless Fragments, i.e. without user interface.

Fragments can be dynamically or statically added to a layout. A Fragment encapsulate functionality so that it is easier to reuse within activity and layouts.

A Fragment component runs in the context of an activity but it has its own lifecycle and their own user interface.

Fragment show or hide

Fragment show or hide

This is the layout that holds two fragments.
You can click on the download link to download the code.

fragment_hide_show.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:gravity="center_horizontal"
    android:layout_width="match_parent" android:layout_height="match_parent">

    <TextView android:layout_width="match_parent" android:layout_height="wrap_content"
        android:gravity="center_vertical|center_horizontal"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:text="Demonstration of hiding and showing fragments." />

    <LinearLayout android:orientation="horizontal" android:padding="4dip"
        android:gravity="center_vertical" android:layout_weight="1"
        android:layout_width="match_parent" android:layout_height="wrap_content">

        <Button android:id="@+id/frag1hide"
            android:layout_width="wrap_content" android:layout_height="wrap_content"
            android:text="Hide" />

        <fragment android:name="com.example.fragmentshowingandhiding.FragmentHideShow$FirstFragment"
                android:id="@+id/fragment1" android:layout_weight="1"
                android:layout_width="0px" android:layout_height="wrap_content" />

    </LinearLayout>

    <LinearLayout android:orientation="horizontal" android:padding="4dip"
        android:gravity="center_vertical" android:layout_weight="1"
        android:layout_width="match_parent" android:layout_height="wrap_content">

        <Button android:id="@+id/frag2hide"
            android:layout_width="wrap_content" android:layout_height="wrap_content"
            android:text="Hide" />

        <fragment android:name="com.example.fragmentshowingandhiding.FragmentHideShow$SecondFragment"
                android:id="@+id/fragment2" android:layout_weight="1"
                android:layout_width="0px" android:layout_height="wrap_content" />

    </LinearLayout>

</LinearLayout>

And this is the xml for the content inside each Fragment.

labeled_text_edit.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    android:padding="4dip" >

    <TextView
        android:id="@+id/msg"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="0"
        android:paddingBottom="4dip" />

    <EditText
        android:id="@+id/saved"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:background="@android:color/holo_blue_light"
        android:freezesText="true"
        android:text="I am in a Fragment" >

        <requestFocus />
    </EditText>

</LinearLayout>

FragmentHideShow.java

package com.example.fragmentshowingandhiding;

import android.app.Activity;
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.Button;
import android.widget.TextView;

/**
 * Demonstration of hiding and showing fragments.
 */
public class FragmentHideShow extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.fragment_hide_show);

        // The content view embeds two fragments; now retrieve them and attach
        // their "hide" button.
        FragmentManager fm = getFragmentManager();
        addShowHideListener(R.id.frag1hide, fm.findFragmentById(R.id.fragment1));
        addShowHideListener(R.id.frag2hide, fm.findFragmentById(R.id.fragment2));
    }

    void addShowHideListener(int buttonId, final Fragment fragment) {
        final Button button = (Button)findViewById(buttonId);
        button.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                FragmentTransaction ft = getFragmentManager().beginTransaction();
                ft.setCustomAnimations(android.R.animator.fade_in,
                        android.R.animator.fade_out);
                if (fragment.isHidden()) {
                    ft.show(fragment);
                    button.setText("Hide");
                } else {
                    ft.hide(fragment);
                    button.setText("Show");
                }
                ft.commit();
            }
        });
    }

    public static class FirstFragment extends Fragment {
        TextView mTextView;

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                Bundle savedInstanceState) {
            View v = inflater.inflate(R.layout.labeled_text_edit, container, false);
            View tv = v.findViewById(R.id.msg);
            ((TextView)tv).setText("The fragment saves and restores this text.");

            // Retrieve the text editor, and restore the last saved state if needed.
            mTextView = (TextView)v.findViewById(R.id.saved);
            if (savedInstanceState != null) {
                mTextView.setText(savedInstanceState.getCharSequence("text"));
            }
            return v;
        }

        @Override
        public void onSaveInstanceState(Bundle outState) {
            super.onSaveInstanceState(outState);

            // Remember the current text, to restore if we later restart.
            outState.putCharSequence("text", mTextView.getText());
        }
    }

    public static class SecondFragment extends Fragment {

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                Bundle savedInstanceState) {
            View v = inflater.inflate(R.layout.labeled_text_edit, container, false);
            View tv = v.findViewById(R.id.msg);
            ((TextView)tv).setText("The TextView saves and restores this text.");

            // Retrieve the text editor and tell it to save and restore its state.
            // Note that you will often set this in the layout XML, but since
            // we are sharing our layout with the other fragment we will customize
            // it here.
            ((TextView)v.findViewById(R.id.saved)).setSaveEnabled(true);
            return v;
        }
    }
}

You can download the complete source code for the above example from here.

How to create layouts that change according to the phone and Tablet in Android Using Fragments in SDK Less than HoneyComb?

Hello all…..

This is a simple tutorial to show how to create a FLEXIBLE UI for both Phone and Tablets in Android.
In the figure below you can see the result after running this tutorial.

Tablet in LANDSCAPE MODE

Fragments

TABLET IN PORTRAIT MODE

Fragments

TABLET IN PORTRAIT MODE – AFTER CLICKING THE LIST.

Fragments

PHONE IN PORTRAIT MODE

Fragments

PHONE IN LANDSCAPE MODE.

Fragments

This can be achieved through Fragments.
This tutorial will have two parts.
1. In the first part I will show you how to use Fragments from API 11 (Honeycomb) and greater.
2. In the second I will show how to change it to adapt to lower versions from 1.6(Donut) using Google’s supporting Library.

I have already covered the first tutorial here..

http://www.coderzheaven.com/2013/02/17/create-layouts-change-phone-tablet-android-fragments/

Please check it before continue reading this post, because there are only small changes in the first post to make it compatible with the older version of Android.

These are the main changes you have to make.
1. Change all Activity to FragmentActivity and change the import statements like below

import android.app.Activity;
to
import android.support.v4.app.FragmentActivity;

2. Change the imports of Fragment from

import android.app.Fragment;
to
import android.support.v4.app.Fragment;

3. Now in the DetailsActivity.java change this line

getFragmentManager().beginTransaction()
.add(android.R.id.content, details).commit();

To

getSupportFragmentManager().beginTransaction()
.add(android.R.id.content, details).commit();

4. match_parent is not supported in old versions so change all “match_parent” in all layouts to “fill_parent”

5. Optionally You can change the min-sdkversion in Manifest to 5.

Done.

Now you have successfully adapted Fragments to the Older version of Android.

How to create layouts that change according to the phone and Tablet in Android Using Fragments?

Hello all…..

This is a simple tutorial to show how to create a FLEXIBLE UI for both Phone and Tablets in Android.
In the figure below you can see the result after running this tutorial.

Tablet in LANDSCAPE MODE

Fragments

TABLET IN PORTRAIT MODE

Fragments

TABLET IN PORTRAIT MODE – AFTER CLICKING THE LIST.

Fragments

PHONE IN PORTRAIT MODE

Fragments

PHONE IN LANDSCAPE MODE.

Fragments

This can be achieved through Fragments.
This tutorial will have two parts.
1. In the first part I will show you how to use Fragments from API 11 (Honeycomb) and greater.
2. In the second I will show how to change it to adapt to lower versions from 1.6(Donut) using Google’s supporting Library.

First Part ( ONLY for HONEYCOMB and GREATER).
(How to use Fragments from API 11 (Honeycomb) and greater)

First we will start with the layout XML Files.
This layout is for the first left part.

left_panel.xml. (Create this XML inside the res/layout folder)

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal" >


    <fragment
        android:id="@+id/titles"
        android:layout_width="0px"
        android:layout_height="match_parent"
        android:layout_weight="1"
        class="com.coderzheaven.googlefragment.TitlesFragment" />

</LinearLayout>

Now create the same copy of this XML inside the res/layout-land folder and change it’s contents slightly to this.
Here we have two fragments because this is used for the landscape mode in the tablets.
So Two fragments will be there at the same time in a single activity.
In the above XML this is not the case since there is only one fragment.

left_panel.xml (inside layout-land folder)

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="horizontal" >

    <fragment
        android:id="@+id/titles"
        android:layout_width="0px"
        android:layout_height="fill_parent"
        android:layout_weight="1"
        class="com.coderzheaven.googlefragment.TitlesFragment" />

    <LinearLayout
        android:id="@+id/details"
        android:layout_width="0px"
        android:layout_height="fill_parent"
        android:layout_weight="2"
        android:background="?android:attr/detailsElementBackground" >
        
        
    </LinearLayout>

</LinearLayout>

The above XML will contain the two layout(fragments) for showing the details while clicking or selecting from the Left Panel for the TABLETS not the PHONES.

So we have to create another XML for showing details in the PHONES.

For that Create a new XML named “details_lay.xml” inside res/layout folder.

details_lay.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal" >


    <LinearLayout
        android:id="@+id/details"
        android:layout_width="0px"
        android:layout_height="match_parent"
        android:layout_weight="1"
        class="com.coderzheaven.googlefragment.DetailsFragment" />

</LinearLayout>

NOTE the class attribute inside the Fragments. It will be pointing to the Class for corresponding Fragments This is the important part in Fragments.
Make sure you change this to your package name before running your project.

Now we will create another layout for content inside the Details (right Panel).
I am naming it “layout_details_content.xml”.

layout_details_content.xml ( this is simply for showing a textview inside the Right Panel, However you can create this dynamically also)
layout_details_content.xml.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical"
    android:layout_gravity="center" >

    <TextView
        android:id="@+id/tv1"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:text="test"
        android:gravity="center" />

</LinearLayout>

OK Now all layouts are complete. Now we will go to the JAVA coding Part.

Remember all Fragments are associated with a java class that extends the Fragment Class.
That’s why we can use Fragments anywhere.

Now the MainActivity that launches First.

MainActivity.java

package com.coderzheaven.googlefragment;

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

public class MainActivity extends Activity {

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.left_panel);
	}

}

The MainActivity has left_panel.xml as layout which will be layout/left_panel.xml in the phones and layout-land/ left_panel.xml in the tablets.
One thing to remember is Tablets will take layout/left_panel.xml while in it’s PORTRAIT mode.

Now we will write the classes for the Fragments.

First we will write class for the List Fragment on the Left.
TitlesFragment.java

package com.coderzheaven.googlefragment;

import android.app.FragmentTransaction;
import android.app.ListFragment;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;

public class TitlesFragment extends ListFragment {
	boolean mDualPane;
	int mCurCheckPosition = 0;

	static String titles[] = { "CoderzHeaven", "Google", "Apple","Android","Microsoft","Samsung" };
 
	@Override 
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);

		// Populate list with our static array of titles.
		setListAdapter(new ArrayAdapter<String>(getActivity(),
				android.R.layout.simple_dropdown_item_1line, titles));

		// Check to see if we have a frame in which to embed the details
		// fragment directly in the containing UI.
		View detailsFrame = getActivity().findViewById(R.id.details);
		mDualPane = detailsFrame != null
				&& detailsFrame.getVisibility() == View.VISIBLE;

		if (savedInstanceState != null) {
			// Restore last state for checked position.
			mCurCheckPosition = savedInstanceState.getInt("curChoice", 0);
		} 

		if (mDualPane) {  
			// In dual-pane mode, the list view highlights the selected item.
			getListView().setChoiceMode(ListView.CHOICE_MODE_SINGLE);
			// Make sure our UI is in the correct state.
			showDetails(mCurCheckPosition);
		}else{
			System.out.println("NOT DUAL");
		}
	}  

	@Override
	public void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
		outState.putInt("curChoice", mCurCheckPosition);
	}

	@Override
	public void onListItemClick(ListView l, View v, int position, long id) {
		showDetails(position);
	}

	/**
	 * Helper function to show the details of a selected item, either by
	 * displaying a fragment in-place in the current UI, or starting a whole new
	 * activity in which it is displayed.
	 */
	void showDetails(int index) { 
		mCurCheckPosition = index;
		if (mDualPane) {
			// We can display everything in-place with fragments, so update
			// the list to highlight the selected item and show the data.
			getListView().setItemChecked(index, true);

			// Check what fragment is currently shown, replace if needed.
			DetailsFragment details = (DetailsFragment) getFragmentManager()
					.findFragmentById(R.id.details);
			if (details == null || details.getShownIndex() != index) {
				// Make new fragment to show this selection.
				details = DetailsFragment.newInstance(index);

				// Execute a transaction, replacing any existing fragment
				// with this one inside the frame.
				FragmentTransaction ft = getFragmentManager()
						.beginTransaction();
				ft.replace(R.id.details, details);
				ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
				ft.commit();
			}

		} else {
			// Otherwise we need to launch a new activity to display
			// the dialog fragment with selected text.
			Intent intent = new Intent();
			intent.setClass(getActivity(), DetailsActivity.class);
			intent.putExtra("index", index);
			startActivity(intent);
		}
	}
}

Note this Line

View detailsFrame = getActivity().findViewById(R.id.details);
		mDualPane = detailsFrame != null
				&& detailsFrame.getVisibility() == View.VISIBLE;

Since for phones there will not be Details Fragment in the first layout as you see in the phones the layout/left_panel.xml is loaded and it has no DETAIL Fragment.

Now we will write class for the DETAIL Fragment.
DetailsFragment.java

package com.coderzheaven.googlefragment;

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

public class DetailsFragment extends Fragment {
	/**
	 * Create a new instance of DetailsFragment, initialized to show the text at
	 * 'index'.
	 */
	static int i = 0;

	public static DetailsFragment newInstance(int index) {
		DetailsFragment f = new DetailsFragment();

		// Supply index input as an argument.
		Bundle args = new Bundle();
		args.putInt("index", index);

		i = index;
		f.setArguments(args);

		return f;
	}

	public int getShownIndex() {
		return getArguments().getInt("index", 0);
	}


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

		View v = getActivity().getLayoutInflater().inflate(
				R.layout.layout_details_content, null);
		TextView tv = (TextView)v.findViewById(R.id.tv1);
		tv.setText(TitlesFragment.titles[i].toUpperCase());
		tv.setTextColor(Color.RED);
		tv.setTextSize(25);
		
		return v;
	}
}

Note this fragement is used By phones and TABLETS while in portrait or LANDSCAPE Mode.
Only difference is when in Phone it is not shown at first since it is not present in the first layout.
Then we will check whether it is in the first layout. If it is there then we are in the LANDSCAPE MODE and if it is not present then we are in the portrait mode in PHONES AND TABLETS. So at that time we will start another DetailActivity which will load the DetaisFragment.

This is the line checking whether second fragment is in the layout or not

View detailsFrame = getActivity().findViewById(R.id.details);
		mDualPane = detailsFrame != null
				&& detailsFrame.getVisibility() == View.VISIBLE;

Here is the Second Activity for PHONES AND TABLETS IN THE PORTRAIT MODE.
DetailsActivity.java

package com.coderzheaven.googlefragment;

import android.app.Activity;
import android.app.Fragment;
import android.content.res.Configuration;
import android.os.Bundle;

public class DetailsActivity extends Activity {

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
			setContentView(R.layout.details_lay); 
			return;
		}

		if (savedInstanceState == null) {
			// During initial setup, plug in the details fragment.
			Fragment details = new DetailsFragment();
			details.setArguments(getIntent().getExtras());
			getFragmentManager().beginTransaction()
					.add(android.R.id.content, details).commit();
		}
	}
}

For you understanding I am also pasting the AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.coderzheaven.googlefragment"
    android:versionCode="1"
    android:versionName="1.0" >
  
    <uses-sdk
        android:minSdkVersion="11"
        android:targetSdkVersion="17" />

    <uses-permission android:name="android.permission.INTERNET"/>
    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.coderzheaven.googlefragment.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity android:name="com.coderzheaven.googlefragment.DetailsActivity"></activity>
    </application>

</manifest>

How to create Swiping Windows in Android from Android 2.1 onwards?

Have you seen the Google Play application in your Android phone. Wondered about how they implemented swiping windows in it.
Don’t Worry, Here is an example which implements it.

Swipe Fragments in Android

Swipe Fragments in Android

Swipe Fragments in Android

Here we will create three pages which can be swiped to access it.

These are the three layouts for the three sections.

section1.xml


    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent" >

        <TextView
            android:id="@+id/textView1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Layout 1" />

    </LinearLayout>

section2.xml


    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent" >

        <TextView
            android:id="@+id/textView1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Layout 2" />

    </LinearLayout>

section3.xml


    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent" >

        <TextView
            android:id="@+id/textView1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Layout 3" />

    </LinearLayout>

Now the java for these layouts. These are also similar , only change is the layout.

Page1.java

package com.example.swipewindows;

import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

public class Page1 extends Fragment {
	Context c;

        public Page1(){
		
	}
	public Page1(Context c) {
		this.c = c;
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View v = inflater.inflate(R.layout.section1, null);
		return       v;
	}
}

Page2.java

package com.example.swipewindows;

import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

public class Page2 extends Fragment {
	Context c;

        public Page2(){
		
	}
	public Page2(Context c) {
		this.c = c;
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View v = inflater.inflate(R.layout.section2, null);

		return v;
	}
}

Page3.java

package com.example.swipewindows;

import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

public class Page3 extends Fragment {
	Context c;

        public Page3(){
		
	}
	public Page3(Context c) {
		this.c = c;
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View v = inflater.inflate(R.layout.section3, null);

		return v;
	}
}

Now the MainActivity.java that uses these sections to join together.

package com.example.swipewindows;

import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;

public class MainActivity extends FragmentActivity {

	/**
	 * The android.support.v4.view.PagerAdapter that will provide fragments for
	 * each of the sections. We use a
	 * android.support.v4.app.FragmentPagerAdapter derivative, which will keep
	 * every loaded fragment in memory. If this becomes too memory intensive, it
	 * may be best to switch to a
	 * android.support.v4.app.FragmentStatePagerAdapter.
	 */
	SectionsPagerAdapter mSectionsPagerAdapter;

	/**
	 * The ViewPager that will host the section contents.
	 */
	ViewPager mViewPager;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main_act);
		// Create the adapter that will return a fragment for each of the three
		// primary sections
		// of the app.
		mSectionsPagerAdapter = new SectionsPagerAdapter(this,
				getSupportFragmentManager());

		// Set up the ViewPager with the sections adapter.
		mViewPager = (ViewPager) findViewById(R.id.pager);
		mViewPager.setAdapter(mSectionsPagerAdapter);

	}

	/**
	 * A FragmentPagerAdapter that returns a fragment corresponding to one of
	 * the primary sections of the app.
	 */
	public class SectionsPagerAdapter extends FragmentPagerAdapter {

		Context c;

		public SectionsPagerAdapter(Context c, FragmentManager fm) {
			super(fm);
			this.c = c;
		}

		@Override
		public Fragment getItem(int i) {
			Fragment fragment = null;
			if (i == 0) {
				fragment = new Page1(c);
			}
			if (i == 1) {
				fragment = new Page2(c);
			}
			if (i == 2) {
				fragment = new Page3(c);
			}
			return fragment; 
		}

		@Override
		public int getCount() {
			return 3;
		}

		@Override
		public CharSequence getPageTitle(int position) {
			switch (position) {
			case 0:
				return getString(R.string.title_section1).toUpperCase();
			case 1:
				return getString(R.string.title_section2).toUpperCase();
			case 2:
				return getString(R.string.title_section3).toUpperCase();
			}
			return null;
		}
	}

}

Now the Strings.xml that contains the section titles.

<resources>

    <string name="app_name">SwipeWindows</string>
    <string name="title_section3">Section 3</string>
    <string name="title_section2">Section 2</string>
    <string name="title_section1">       Section 1      </string>
    <string name="hello_world">Hello world!</string>
    <string name="menu_settings">     Settings   </string>
    <string name="title_activity_main">SwipeActivity</string>

</resources>

Download the complete source from here.