Saturday, 6 July 2013

Full example of using Fragment in Android Development

Fragment in Android is very useful for responsive layout design. In the post, I will give you a full detailed example of using FramentActivity in android application development.

We will produce a demo application which have two different layouts in different device.


(1) Let's see the vertical layout first. We use FrameLayout to hold two fragment of LinearLayout container.
<FrameLayout 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" >  
      
     
    <LinearLayout   
        android:id="@+id/list_container"  
        android:layout_width="match_parent"  
        android:layout_height="match_parent">  
    </LinearLayout>  
      
      
    
    <LinearLayout   
        android:id="@+id/detail_container"  
        android:layout_width="match_parent"  
        android:layout_height="match_parent">  
    </LinearLayout>  
  
</FrameLayout>  
(2) For landscape layout, we create a layout-land folder under the res folder. Then we create the same layout.xml
<LinearLayout 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" >  
      
    
    <LinearLayout   
        android:id="@+id/list_container"  
        android:layout_width="match_parent"  
        android:layout_height="match_parent"  
        android:layout_weight="2">  
    </LinearLayout>  
      
      
    
    <LinearLayout   
        android:id="@+id/detail_container"  
        android:layout_width="match_parent"  
        android:layout_height="match_parent"  
        android:layout_weight="1">  
    </LinearLayout>  
  
</LinearLayout>  
(3) create a new fragment which contains a ListView to show the master data.
package com.easyinfogeek.fragmentExample;  
  
import java.util.ArrayList;  
import java.util.List;  
  
import android.content.res.Configuration;  
import android.os.Bundle;  
import android.support.v4.app.Fragment;  
import android.support.v4.app.FragmentManager;  
import android.support.v4.app.FragmentManager.OnBackStackChangedListener;  
import android.support.v4.app.FragmentTransaction;  
import android.view.LayoutInflater;  
import android.view.View;  
import android.view.ViewGroup;  
import android.widget.AdapterView;  
import android.widget.AdapterView.OnItemClickListener;  
import android.widget.ArrayAdapter;  
import android.widget.ListView;  
import android.widget.Toast;  
  
/** 
 * 
 * @author easinfogeek.com 
 * 
 */  
public class FragmentList extends Fragment {  
      
    private List<String> mDataSourceList = new ArrayList<String>();  
    private List<FragmentTransaction> mBackStackList = new ArrayList<FragmentTransaction>();  
  
  
    @Override  
    public View onCreateView(LayoutInflater inflater, ViewGroup container,  
            Bundle savedInstanceState) {  
        return inflater.inflate(R.layout.fragment_list_layout, container, false);  
    }  
      
      
    @Override  
    public void onActivityCreated(Bundle savedInstanceState) {  
        super.onActivityCreated(savedInstanceState);  
          
        //add data to ListView  
        for(int i=0, count=20; i<count; i++){  
            mDataSourceList.add("列表数据" + i);  
        }  
          
        
        ListView listView = (ListView) getActivity().findViewById(R.id.fragment_list);  
        listView.setAdapter(new ArrayAdapter(getActivity(), android.R.layout.simple_list_item_1, mDataSourceList));  
          
        listView.setOnItemClickListener(new OnItemClickListener() {  
  
            @Override  
            public void onItemClick(AdapterView<?> parent, View view,  
                    int position, long id) {  
                //create a Fragment  
                Fragment detailFragment = new FragmentDetail();  
                  
              
                Bundle mBundle = new Bundle();  
                mBundle.putString("arg", mDataSourceList.get(position));  
                detailFragment.setArguments(mBundle);  
                  
                final FragmentManager fragmentManager = getActivity().getSupportFragmentManager();  
                final FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();  
                  
                //check if the device is landscape or portrait 
                Configuration configuration = getActivity().getResources().getConfiguration();  
                int ori = configuration.orientation;  
                  
                fragmentTransaction.replace(R.id.detail_container, detailFragment);  
                  
                if(ori == configuration.ORIENTATION_PORTRAIT){  
                    fragmentTransaction.addToBackStack(null);  
                }  
                  
                fragmentTransaction.commit();  
                  
                  
            }  
        });  
          
    }  
      
    /** 
     *  
     * @param msg 
     */  
    private void showTost(String msg){  
        Toast.makeText(getActivity(), msg, Toast.LENGTH_LONG).show();  
    }  
  
}  
(4) Create a detail fragment which show the detail of each record
package com.easyinfogeek.fragmentExample;  
  
import java.util.ArrayList;  
import java.util.List;  
  
import android.content.res.Configuration;  
import android.os.Bundle;  
import android.support.v4.app.Fragment;  
import android.view.LayoutInflater;  
import android.view.View;  
import android.view.ViewGroup;  
import android.widget.ArrayAdapter;  
import android.widget.LinearLayout;  
import android.widget.ListView;  
  
/** 
 * 
 * @author easinfogeek.com 
 * 
 */  
public class FragmentDetail extends Fragment {  
  
    @Override  
    public View onCreateView(LayoutInflater inflater, ViewGroup container,  
            Bundle savedInstanceState) {  
        return inflater.inflate(R.layout.fragment_detail_layout, container, false);  
    }  
      
      
    @Override  
    public void onActivityCreated(Bundle savedInstanceState) {  
        super.onActivityCreated(savedInstanceState);  
          
        //get the data from the master list  
        Bundle bundle = getArguments();  
        String data = bundle.getString("arg");  
          
        List<String> list = new ArrayList<String>();  
        for(int i=0, count=20; i<count; i++){  
            list.add(data);  
        }  
          
        LinearLayout layout = (LinearLayout) getActivity().findViewById(R.id.detail_container);  
          
        ListView listView = (ListView) getActivity().findViewById(R.id.fragment_detail);  
        listView.setAdapter(new ArrayAdapter(getActivity(), android.R.layout.simple_list_item_1, list));  
          
        Configuration configuration = getActivity().getResources().getConfiguration();  
        int ori = configuration.orientation;  
      
    }  
  
}  
(5) Finally, create the activiy for the application
package com.easyinfogeek.fragmentExample;  
  
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.FragmentTransaction;  
  
public class MainActivity extends FragmentActivity {  
  
    @Override  
    protected void onCreate(Bundle savedInstanceState) {  
        super.onCreate(savedInstanceState);  
        setContentView(R.layout.activity_main);  
          
        /Master data list Fragment  
        Fragment listFragment = new FragmentList();  
          
        FragmentManager fragmentManager = getSupportFragmentManager();  
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();  
        fragmentTransaction.add(R.id.list_container, listFragment);  
          
        fragmentTransaction.commit();  
    }  
  
      
  
}  

10 comments:

  1. Excellent information, thanks for sharing great information. We deal with Android App Development this information is quite informative and interesting.

    ReplyDelete
  2. Hi,
    Thanks for ur post.can u post the source code?

    ReplyDelete
  3. Thanks for your code...can u explain in detail?...

    ReplyDelete
  4. Hi, It seems the xml layouts are not complete and some of them must be definetively missing, isn't it?

    ReplyDelete
  5. "Full Example" is misleading, code above is incomplete.

    ReplyDelete
  6. can you give me details for using this XML files.....

    ReplyDelete
  7. It's very nice article. Thank you very much for posting....

    ReplyDelete
  8. You saved my life! :D

    ReplyDelete
  9. Thanks a lot friend.

    ReplyDelete
  10. Thank you for this Example program..thanx a lot

    ReplyDelete