Showing posts with label Compatibility Package. Show all posts
Showing posts with label Compatibility Package. Show all posts

Saturday, April 16, 2011

Using Fragment of Android Compatibility Package

The Android 3.0 introduce a awesome feature Fragment.
It really helpful when we design for tablet. You can refer The Android 3.0 Fragment API   for more details
Here I'm going to explain how to use Fragment for lower version.
Now android had released a static library that exposes the same Fragments API, so that applications compatible with Android 1.6 or later can use fragments to create tablet-compatible user interfaces.

For this you need to do follow these steps
  • Add android-support-v4.jar to you project
    • You can found this jar at yoursdkpath/extras/android/compatibility/v4/
    • Copy this into your libs folder in the root of your project 
    • add this jar to your project build path
  • In order to use this you need to use FragmentActivity instead of Activity 
    • public class Home extends FragmentActivity
  • To get FragmentManager 
    • Need to use getSupportFragmentManager instead of getFragmentManage
The complete code will look like this

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentTransaction;
public class Home extends FragmentActivity{
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
  Fragment productDetails = new MyFragment();
  fragmentTransaction.replace(R.id.mainFragement, productDetails);
  fragmentTransaction.commit();
    }
}
MyFragment.java

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

public class MyFragment extends Fragment{
 public MyFragment(){
  Log.i("MYEXPENSETRACKER","MyFragment ()");
 }
 @Override
 public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
  TextView t = new TextView(getActivity());
  t.setText("From Fragement");
  return t;
 }
}

The main.xml I used

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
<TextView  
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:text="@string/hello"
    />
    
 <FrameLayout
  android:id="@+id/mainFragement"
  android:layout_width="wrap_content"
  android:layout_height="wrap_content">
 </FrameLayout>
</LinearLayout>

Hope it helped you..:)