Sunday, December 11, 2011

A simple exercise of Fragment, inflate layout from XML

A simple exercise of Fragment, inflate layout from XML

Create a new Android project target Android 3.0.

Modify layout, main.xml, to add a our fragment.
<?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="horizontal" >

<TextView
android:layout_width="0px"
android:layout_weight="1"
android:layout_height="match_parent"
android:text="It's TextView in main Activity"
android:background="#555555"/>
<fragment
class="com.exercise.FragmentTest.MyFragment"
android:id="@+id/myfragment"
android:layout_width="0px"
android:layout_weight="4"
android:layout_height="match_parent" />

</LinearLayout>


Implement /res/layout/fragmentlayout.xml, to define the layout of our fragment.
<?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" >
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="It's Fragment" />
<ImageView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:src="@drawable/ic_launcher"/>
</LinearLayout>


Add a new class MyFragment extends Fragment. Inside onCreateView(), inflate R.layout.fragmentlayout to generate our view and return it.
package com.exercise.FragmentTest;

import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

public class MyFragment extends Fragment {

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
View myFragmentView = inflater.inflate(R.layout.fragmentlayout, container, false);

return myFragmentView;
}

}


Keep the main activity no change from the auto-generated version.

Related article:
- Programmatically add fragment



4 comments:

priya said...

I wish I found this article when I started to learn fragments.

avs said...

great example, thanks!

Anonymous said...

Thanks. it helped.

Anonymous said...

good example...i appreciate your example..