Saturday 29 September 2012

Animation Prior to Android 3.0

Before Android 3.0, we have View Animation which covers:

1. Tween Animation

Tween animation calculates the animation with information such as the start point, end point, size, rotation, and other common aspects of an animation.

A sequence of animation instructions defines the tween animation, defined by either XML or Android code. As with defining a layout, an XML file is recommended because it's more readable, reusable, and swappable than hard-coding the animation.


The animation XML file belongs in the res/anim/ directory of your Android project. The file must have a single root element: this will be either a single <alpha><scale><translate><rotate>, interpolator element, or<set> element that holds groups of these elements (which may include another <set>).


Note:

Be sure to use the proper format for what you want ("50" for 50% relative to the parent, or "50%" for 50% relative to itself).

Using translate animation we can do animation like slide left, slide right, slide up, slide down, shake etc.


slide_left.xml




<?xml version="1.0" encoding="utf-8"?>
<translate
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:fromXDelta="0%"
    android:toXDelta="-100%"
    android:interpolator="@android:anim/linear_interpolator"
    android:duration="2000" />


slide_right.xml


<?xml version="1.0" encoding="utf-8"?>
<translate
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:fromXDelta="0%"
    android:toXDelta="100%"
    android:interpolator="@android:anim/linear_interpolator"
    android:duration="2000" />

slide_up.xml



<?xml version="1.0" encoding="utf-8"?>
<translate xmlns:android="http://schemas.android.com/apk/res/android"
    android:fromYDelta="0%"
    android:toYDelta="-100%"
    android:duration="2000"
    android:interpolator="@android:anim/linear_interpolator" />


slide_down.xml


<?xml version="1.0" encoding="utf-8"?>
<translate
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:fromYDelta="0%"
    android:toYDelta="100%"
    android:duration="2000"
    android:interpolator="@android:anim/linear_interpolator" />

shake.xml




<?xml version="1.0" encoding="utf-8"?>
<translate
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:fromXDelta="0"
    android:toXDelta="100"
    android:duration="1000"
    android:interpolator="@android:anim/cycle_interpolator"
    android:repeatCount="50"
    android:repeatMode="reverse" />


Note:

To implement shake behaviour we need to use cycle interpolator and repeatCount attribute. 



Using rotate animation we can do rotation with different angles and points.


rotate_360.xml


<?xml version="1.0" encoding="utf-8"?>
<rotate
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:fromDegrees="0"
    android:toDegrees="360"
    android:pivotX="50%"
    android:pivotY="50%"
    android:interpolator="@android:anim/linear_interpolator"
    android:duration="2000" />

Note:




android:pivotX
Float. The X coordinate to remain fixed when the object is scaled.
android:pivotY
Float. The Y coordinate to remain fixed when the object is scaled.


Using alpha animation we can do fade in/ fade out animation.

fade_in.xml




<?xml version="1.0" encoding="utf-8"?>
<alpha
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:fromAlpha="0"
    android:toAlpha="1"
    android:interpolator="@android:anim/linear_interpolator"
    android:duration="2000" />


fade_out.xml



<?xml version="1.0" encoding="utf-8"?>
<alpha
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:duration="2000"
    android:fromAlpha="1"
    android:interpolator="@android:anim/linear_interpolator"
    android:toAlpha="0" />


Loading View Animation:


Animation animation = AnimationUtils.loadAnimation(this, R.anim.yourAnim);
animation.startAnimation(animation);

2. Frame by Frame Animation

Drawable animation lets you load a series of Drawable resources one after another to create an animation.

frame_animation.xml



<?xml version="1.0" encoding="utf-8"?>
<animation-list xmlns:android="http://schemas.android.com/apk/res/android"
    android:oneshot="false">
    <item android:drawable="@drawable/active" android:duration="500" />
    <item android:drawable="@drawable/deactive" android:duration="500" />
</animation-list>


Note:
By setting the android:oneshot attribute of the list to true, it will cycle just once then stop and hold on the last frame.

Loading Frame Animation:



@Override
public void onWindowFocusChanged(boolean hasFocus) {
  // TODO Auto-generated method stub
super.onWindowFocusChanged(hasFocus);
((AnimationDrawable)view.getBackground()).start();
}



profile for Vineet Shukla at Stack Overflow, Q&A for professional and enthusiast programmers

Thursday 23 August 2012

Passing Data Object from one Activity to Another

We often need to pass data model from one activity to another. For this Android provides a way to do this and it is called Parcelable.

Using parcelable we can pass different types of data:

1. int and int[]
2. float and float[]
3. double and double[]
4. byte and byte[]
5. boolean[]
6. long and long[]
7. String and String[]
8. Object and Object[]
9. List and List<T>
10. Map
11. Nested data model and many more.

Below I am covering some basic types and rest you can try on your own.

Create a data Model: TestModel


public class TestModel implements Parcelable{

public int testInt;
public Double testDouble;
public String testString;
public boolean testBoolean;
private byte testByte;

public TestModel() {
testInt = 0;
testDouble = 0.0;
testString = "";
testBoolean = false;
testByte = 0;
}

//Get your data here in the same order in which you have set it. public TestModel(Parcel in) {
testInt = in.readInt();
testDouble = in.readDouble();
testString = in.readString();
boolean[] flag = new boolean[1];
in.readBooleanArray(flag);
testBoolean = (flag[0] == true)? true : false;
testByte = in.readByte();
}

public int getTestInt() {
return testInt;
}

public void setTestInt(int testInt) {
this.testInt = testInt;
}

public Double getTestDouble() {
return testDouble;
}

public void setTestDouble(Double testDouble) {
this.testDouble = testDouble;
}

public String getTestString() {
return testString;
}

public void setTestString(String testString) {
this.testString = testString;
}

public boolean isTestBoolean() {
return testBoolean;
}

public void setTestBoolean(boolean testBoolean) {
this.testBoolean = testBoolean;
}

public byte getTestByte() {
return testByte;
}

public void setTestByte(byte testByte) {
this.testByte = testByte;
}

//Write your data here

public void writeToParcel(Parcel dest, int flags) {
dest.writeInt(testInt);
dest.writeDouble(testDouble);
dest.writeString(testString);
dest.writeBooleanArray(new boolean[]{testBoolean});
dest.writeByte(testByte);

}

public static final Parcelable.Creator<TestModel> CREATOR = new Parcelable.Creator<TestModel>()
{
public TestModel createFromParcel(Parcel in)
{
return new TestModel(in);
}
public TestModel[] newArray(int size)
{
return new TestModel[size];
}
};

public int describeContents() {
// TODO Auto-generated method stub
return 0;
}

}

Passing data model to another Activity:
//Setting data in the model
TestModel  model = new TestModel ();
//Set values in the model...

//Create intent

Intent intent = new Intent(getApplicationContext(),YourActivity.class);
Bundle bundle = new Bundle();                //create bundle..
bundle.putParcelable("data",  model  );    
intent.putExtras(bundle);                    //set the bundle..
startActivity(intent);

Get the data in the Activity:




Bundle bundle = getIntent().getExtras();
TestModel  model = bundle.getParcelable("data");


profile for Vineet Shukla at Stack Overflow, Q&A for professional and enthusiast programmers

Sunday 22 July 2012

Working with HttpsUrlConnection


Refer this doc over HttpsUrlConnection.
To create key and import certificate use Portecle tool.
To create key using Keytool, follow the doc.


String query = "emailId=" + URLEncoder.encode("xxx@gmail.com", HTTP.UTF_8) + "&pwd=" + URLEncoder.encode("password", HTTP.UTF_8);


HttpsURLConnection urlConnection = null;
try{
    KeyStore keyStore = KeyStore.getInstance("BKS");
    InputStream in =  
    getResources().openRawResource(R.raw.keystore);
    keyStore.load(in, "password".toCharArray());
    TrustManagerFactory tmf = 
    TrustManagerFactory.getInstance("X509");
    tmf.init(keyStore);


    SSLContext context = SSLContext.getInstance("TLS");
    context.init(null, tmf.getTrustManagers(), null);
    System.setProperty("http.keepAlive", "false");
    URL url = new URL("https://www.google.co.in/");
    urlConnection = (HttpsURLConnection) url.openConnection();
     
urlConnection.setSSLSocketFactory(context.getSocketFactory());
    urlConnection.setDoInput(true);
    urlConnection.setDoOutput(true);
    urlConnection.setRequestMethod("POST");
    urlConnection.setRequestProperty("content-type",
    "application/x-www-form-urlencoded");
    urlConnection.setRequestProperty("Content-length", "" +  query.getBytes().length);

     //To post data...
     DataOutputStream output = new DataOutputStream( urlConnection.getOutputStream() );
     output.writeBytes( query );
     output.flush();
     output.close();

     InputStream stream = null;


     if ( urlConnection.getResponseCode() == 201 )
stream = urlConnection.getInputStream();
     else
       //Report error...

     urlConnection.disconnect();


}catch(Exception e){
     urlConnection.disconnect();
}



profile for Vineet Shukla at Stack Overflow, Q&A for professional and enthusiast programmers

Thursday 5 July 2012

WebView Settings


Note: To know the HTML5 browser support for your device, you only need to open the url in your browser: http://html5test.com/


WebSettings settings = mWebView.getSettings();
//To enable the built-in zoom
settings.setBuiltInZoomControls(true);


//To enable JavaScript
settings.setJavaScriptEnabled(true);


//To enable Plugin
settings.setPluginState(PluginState.ON);


Plugin:
plug-ins are commonly used in web browsers to play video, 
scan for viruses, and display new file types. 
Well-known plug-ins examples include 
Adobe Flash Player, QuickTime, and Microsoft Silverlight.


//To enable or disable file access within WebView. 
//File access is enabled by default.
settings.setAllowFileAccess(true);


//To enable dom storage
//DOM Storage is a way to store meaningful amounts of 
//client-side data in a persistent and secure manner.
settings.setDomStorageEnabled(true);


//To enable wide viewport.
settings.setUseWideViewPort(true);


//To enable JavaScript to open windows automatically.
settings.setJavaScriptCanOpenWindowsAutomatically(true);


//To enable twitter, youtube etc.
settings.setUserAgentString("Mozilla/5.0 (Linux; U; Android 2.0; en-us; Droid Build/ESD20) 
AppleWebKit/530.17 (KHTML, like Gecko) Version/4.0 Mobile Safari/530.17");


Detailed Description: WebSettingsWebView
profile for Vineet Shukla at Stack Overflow, Q&A for professional and enthusiast programmers

Monday 25 June 2012

Programmatically add Image to Gallery


private void addPicToGallery() {
    Intent media = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);


//mCurrentPhotoPath is the path to image.
    File f = new File(mCurrentPhotoPath);
    Uri contentUri = Uri.fromFile(f);
    media.setData(contentUri);
    this.sendBroadcast(media);
}
profile for Vineet Shukla at Stack Overflow, Q&A for professional and enthusiast programmers

Monday 12 March 2012

Single textview with multiple action

We can use single textview for:

1.  Different textsizes.
2.  Different colors.
3.  Click event.
4.  Linking with URL etc.

private void prepareStylishText ( TextView view ) {
        SpannableStringBuilder spanTxt = new SpannableStringBuilder("Different");

        //set the text clickable.
        spanTxt.setSpan(new ClickableSpan() {

            @Override
            public void onClick(View widget) {
                // TODO Auto-generated method stub
                Toast.makeText(getApplicationContext(), "Different style text in android.",
                        Toast.LENGTH_SHORT).show();
            }
        },
                0, spanTxt.length(), 0 );

        //set the text color.
        spanTxt.setSpan(new ForegroundColorSpan(Color.RED),
                0, spanTxt.length(), 0 );

        //add more text.
        spanTxt.append(" style");
        spanTxt.setSpan(new ForegroundColorSpan(Color.BLUE),
            spanTxt.length() - " style".length(), spanTxt.length(), 0 );

        spanTxt.append(" text with single textview in");

        spanTxt.setSpan(new ForegroundColorSpan(Color.BLACK),
            spanTxt.length() - " text with single textview in".length(), spanTxt.length(), 0 );

        spanTxt.append(" android.");

        //make the textsize 2 times.
        spanTxt.setSpan(new RelativeSizeSpan(2f), spanTxt.length() - " android".length(), spanTxt.length(), 0  );

        //make the link.
        spanTxt.setSpan(new URLSpan("http://developer.android.com/index.html"), spanTxt.length() - " android".length(), spanTxt.length(), 0 );

        //set the color after the link else the link color will override it.
        spanTxt.setSpan(new ForegroundColorSpan(Color.GREEN),
                spanTxt.length() - " android".length(), spanTxt.length(), 0 );

        //make click and url to work.
        view.setMovementMethod(LinkMovementMethod.getInstance());
        view.setText(spanTxt, BufferType.SPANNABLE);
    }

Output:
 Note: You can also use SpannableString in place of SpannableStringBuilder.

profile for Vineet Shukla at Stack Overflow, Q&A for professional and enthusiast programmers

Tuesday 6 March 2012

Fragment Dialog and Date-Time Picker

With the fragment use we often need to use dialog with fragment. Here we will see how to use dialog with fragment and How to use Date-Time picker with the fragment.

Note: Check Fragment.

1. Extend DialogFragment:

public class CustomDialogFragment extends DialogFragment{
       //Define constants for date-time picker.
       public final int DATE_PICKER = 1;
       public final int TIME_PICKER = 2;
       public final int DIALOG = 3;
}

2. Add constructor with Fragment argument as It will let know over which fragment, the dialog should be shown.

private Fragment mCurrentFragment;
public CustomDialogFragment ( Fragment fragment ) {
        mCurrentFragment = fragment;
}

3.  Override onCreateDialog:

public Dialog onCreateDialog(Bundle savedInstanceState) {
        Bundle bundle = new Bundle();
        bundle = getArguments();
        int id = bundle.getInt("dialog_id");
        switch (id) {
        case DATE_PICKER:
            return new DatePickerDialog(getActivity(),
                    (OnDateSetListener)mCurrentFragment, bundle.getInt("year"),
                    bundle.getInt("month"), bundle.getInt("day"));
   
       case TIME_PICKER:
            return new TimePickerDialog(getActivity(),
                    (OnTimeSetListener)mCurrentFragment,          bundle.getInt("hour"),
                    bundle.getInt("minute"), false);
        }

       case DIALOG:
       //Define your custom dialog or alert dialog here and return it.
       return dialog;
    }

Note: Implement OnDateSetListener, OnTimeSetListener on Fragment.

4. Show the dialog:

CustomDialogFragment dialog = new CustomDialogFragment(YourFragment.this);
Bundle bundle = new Bundle();
bundle.putInt("dialog_id", DATE_PICKER);
bundle.putInt("year", mYear);
bundle.putInt("month", mMonth);
bundle.putInt("day", mDay);
dialog.setArguments(bundle);
dialog.show(getFragmentManager(), "dialog");

Note: For detail description follow the link.

profile for Vineet Shukla at Stack Overflow, Q&A for professional and enthusiast programmers

Monday 5 March 2012

Useful stuff

Here is nothing new but I wanted to bind some useful stuff that I could not find in one place.

1. Invoke the device's gallery and get the Image/video URI. 

private void invokeGallery () {
     Intent intent = new Intent();
     intent.setAction(Intent.ACTION_PICK);
     intent.setType("image/*");
     startActivityForResult(intent, 001);
}

   @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        // TODO Auto-generated method stub
        super.onActivityResult(requestCode, resultCode, data);
        if ( requestCode == 001 && data != null && data.getData() != null ) {
            URi imageUri = data.getData();
            imageview.setImageURI(imageUri );
        }
    }

2. Launch default contact picker and get the contact details.

private void launchContactPicker() {
        Intent contactPickerIntent = new Intent(Intent.ACTION_PICK,
                Contacts.CONTENT_URI);
        startActivityForResult(contactPickerIntent, 1001);
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
   if ( requestCode == 1001 ) {
      Bundle _data = data.getExtras();
      Set<String> keys = _data.keySet();
      Iterator<String> iterate = keys.iterator();
      if ( iterate.hasNext() ) {
         String key = iterate.next();
         String contactName = _data.get(key).toString();
      //To query Content Provider for contact number:
      Cursor cursor = getContentResolver().query(android.provider.ContactsContract.Contacts.CONTENT_URI, null,    android.provider.ContactsContract.Contacts.DISPLAY_NAME + "=?", new String[]{contactName }, null);    
      //To query the Content Provider for Email ID's:

      //Using above cursor:
      String id = cursor .getString(cursor .getColumnIndex(android.provider.ContactsContract.Contacts._ID));
      Cursor emailCursor = getContentResolver().query(android.provider.ContactsContract.CommonDataKinds.Email.CONTENT_URI, null, android.provider.ContactsContract.CommonDataKinds.Email.CONTACT_ID+ " = " + id, null, null);

      if(emailCursor .getCount() > 0){
         emailCursor .moveToFirst();
         do {
             String _emailId = emailCursor.getString(emailCursor        .getColumnIndex(android.provider.ContactsContract.CommonDataKinds.Email.DATA));            }while(mCursor.moveToNext());
        }

            }
        }
}

3. Get device resolution and desity.

DisplayMetrics metrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(metrics);
 //Desity
switch(metrics.densityDpi){
    case DisplayMetrics.DENSITY_LOW:
         break;
    case DisplayMetrics.DENSITY_MEDIUM:
         break;
    case DisplayMetrics.DENSITY_HIGH:
         break;
}
//Resolution
int screenWidth = metrics .widthPixels;
int screenHeight = metrics .heightPixels;

profile for Vineet Shukla at Stack Overflow, Q&A for professional and enthusiast programmers

Friday 10 February 2012

Fragments

Fragments are very useful in modularizing the code and UI. Fragment's use increases reusability in the project.

In this tutorial:

1.  How to use fragments with activity.
2.  Getting click events in the activity from fragments.
3.  Passing data from activity to fragments and fragments to fragments.
4.  Replacing fragments from activity and from fragment to fragment.

Note:
Here we will create one activity MainActivity and 3 fragments MainFragment, InputFragment, DetailFragment.
We will take some input from user in one fragments and will show the entered values in another fragments.

Let's start:

1.  Create a android project.
2.  Create a MainActivity.

MainActivity.java
public class MainActivity extends FragmentActivity implements ActivityListener{
    /** Called when the activity is first created.
     *  ActivityListener is the interface which is used
     *  to get callback from fragment.
     */

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        //Fragments are added programmatically here...
        MainFragment fragment = new MainFragment();
        FragmentManager fragmentManager = getSupportFragmentManager();
        FragmentTransaction transaction = fragmentManager.beginTransaction();
        transaction.add(R.id.frameLayout, fragment);
        transaction.commit();

    }

    public void getData(Bundle bundle) {
        if ( bundle != null ) {
            FragmentManager fragmentManager = getSupportFragmentManager();
            DetailFragment detailFragment = new DetailFragment();
            detailFragment.setArguments(bundle);
            FragmentTransaction transaction = fragmentManager.beginTransaction();
            transaction.replace(R.id.frameLayout, detailFragment);
            transaction.commit();
        }
    }

}

main.xml
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical"
    android:id="@+id/frameLayout" >

</FrameLayout>

Note: To add fragments inside xml:

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical"
    android:id="@+id/frameLayout" >

<fragment 
  android:name="com.fragmentdemo.fragment.MainFragment"
  android:id="@+id/fragment"
  android:layout_weight="1"
  android:layout_width="0dp"
  android:layout_height="fill_parent" />

</FrameLayout>

3.  Create MainFragment.

MainFragment.java

public class MainFragment extends Fragment{

    private Button mInput;
   /**
     * Define Click listener for the button.
     */
    private OnClickListener inputClickListener = new OnClickListener() {
        public void onClick(View v) {
            FragmentManager fragmentManager = getFragmentManager();
            InputFragment inputFragment = new InputFragment();
            FragmentTransaction transaction = fragmentManager.beginTransaction();
            transaction.replace(R.id.frameLayout, inputFragment);
            transaction.addToBackStack(null);
            transaction.commit();
        }
    };

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        View contentView = inflater.inflate(R.layout.main_frag, null);
        contentView.setDrawingCacheEnabled(false);

        mInput = (Button)contentView.findViewById(R.id.btnInput);

        return contentView;
    }

    @Override
    public void onStart() {
        super.onStart();
        mInput.setOnClickListener(inputClickListener);
    }

}

main_frag.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:gravity="center"
    android:orientation="vertical" >

    <Button
        android:id="@+id/btnInput"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Add User Details"
        android:textSize="20dp" />

</LinearLayout>

4.  Create InputFragment.

InputFragment.java

public class InputFragment extends Fragment{

    private ActivityListener mListener;
    private Button mSubmit;
    private EditText mName, mOccupation, mDesignation;

    private OnClickListener submitClickListener = new OnClickListener() {
        public void onClick(View v) {
            if (mName.getText().toString().trim().length() == 0|| mOccupation.getText().toString().trim().length() == 0 || mDesignation.getText().toString().trim().length() == 0 ) {
            Toast.makeText( getActivity(), "Field can not be left empty.", Toast.LENGTH_SHORT).show();
            }
            else {
                Bundle bundle = new Bundle();
                bundle.putString("name", mName.getText().toString());
                bundle.putString("occupation", mOccupation.getText().toString());
                bundle.putString("designation", mDesignation.getText().toString());

        //Method1: Pass data to activity and then to fragment.
                if ( mListener != null )
                    mListener.getData(bundle);

        //Method2: pass data to fragment directly.
        FragmentManager fragmentManager = getFragmentManager();
        DetailFragment detailFragment = new DetailFragment();
        detailFragment.setArguments(bundle);
        FragmentTransaction transaction = fragmentManager.beginTransaction();
                transaction.replace(R.id.frameLayout, detailFragment);
        transaction.remove(InputFragment.this);
        transaction.commit();
            }
        }
    };

    //Check for interface if activity has implemented it or not.
    @Override
    public void onAttach(Activity activity) {
        // TODO Auto-generated method stub
        super.onAttach(activity);
        try {
            mListener = (ActivityListener)activity;
        }catch (ClassCastException e) {
            Toast.makeText( activity, "Activity must implement this interface.", Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        View contentView = inflater.inflate(R.layout.input_frag, null);
        contentView.setDrawingCacheEnabled(false);

        mSubmit = (Button)contentView.findViewById(R.id.btnSubmit);
        mName = (EditText)contentView.findViewById(R.id.editName);
        mOccupation = (EditText)contentView.findViewById(R.id.editOccupation);
        mDesignation = (EditText)contentView.findViewById(R.id.editDesignation);

        Bundle bundle = getArguments();
        if ( bundle != null ) {
            mName.setText(bundle.getString("name"));
            mOccupation.setText(bundle.getString("occupation"));
            mDesignation.setText(bundle.getString("designation"));
        }
        return contentView;
    }

    @Override
    public void onStart() {
         super.onStart();
        mSubmit.setOnClickListener(submitClickListener);
    }

    //Define Interface for callback to activity.
    public interface ActivityListener {
        public void getData (Bundle bundle);
    }

}

input_frag.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:padding="20dp" >

    <TextView
        android:id="@+id/name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Name"
        android:textSize="20dp" />

    <EditText
        android:id="@+id/editName"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:hint="Enter your name"
        android:textSize="20dp"
        android:padding="10dp"
        android:layout_marginTop="20dp" />

    <TextView
        android:id="@+id/occupation"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Occupation"
        android:textSize="20dp"
        android:layout_marginTop="20dp" />

    <EditText
        android:id="@+id/editOccupation"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:hint="Enter your Occupation"
        android:textSize="20dp"
        android:padding="10dp"
        android:layout_marginTop="20dp" />

    <TextView
        android:id="@+id/designation"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Designation"
        android:textSize="20dp"
        android:layout_marginTop="20dp" />

    <EditText
        android:id="@+id/editDesignation"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:hint="Enter your Designation"
        android:textSize="20dp"
        android:padding="10dp"
        android:layout_marginTop="20dp" />

    <Button
        android:id="@+id/btnSubmit"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Submit"
        android:textSize="20dp"
        android:layout_marginTop="20dp" />

</LinearLayout>

5.  Create DetailFragment.

DetailFragment.java

public class DetailFragment extends Fragment{

    private TextView mInfo;
    private Button mEditDetail, mClose;
    private Bundle mBundleData;

    private OnClickListener editClickListener = new OnClickListener() {
        public void onClick(View v) {
            InputFragment inputFragment = new InputFragment();
            inputFragment.setArguments(mBundleData);
            getFragmentManager().beginTransaction().
            replace(R.id.frameLayout, inputFragment).addToBackStack(null).commit();
        }
    };

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        View contentView = inflater.inflate(R.layout.detail_frag, null);
        contentView.setDrawingCacheEnabled(false);

        mInfo = (TextView)contentView.findViewById(R.id.detail);
        mEditDetail = (Button)contentView.findViewById(R.id.btnEdit);
        mBundleData = getArguments();
        if ( mBundleData != null ) {
            mInfo.setText("Name:  " + mBundleData.getString("name") + "\n"
                    + "Occupation:  " + mBundleData.getString("occupation") + "\n"
                    + "Designation:  " + mBundleData.getString("designation") + "\n" );
        }
        return contentView;
    }

    @Override
    public void onStart() {
        super.onStart();
        mEditDetail.setOnClickListener(editClickListener);
    }

}

detail_frag.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:gravity="center" >

    <TextView
        android:id="@+id/detail"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="20dp" />

    <Button
        android:id="@+id/btnEdit"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Edit User Details"
        android:textSize="20dp" />

</LinearLayout>

Source:

profile for Vineet Shukla at Stack Overflow, Q&A for professional and enthusiast programmers