android fragment example

In this post i am going to present a simple example about fragments in android. In this example there are  two fragments presents, and add them into the main activity using two separate relative layouts. There are two buttons on the main activity, first button is for open the first fragment and by clicking the second button user can open the second fragment.
Ads By Google




MainActivity.java
1:  public class MainActivity extends Activity {  
2: Button B1,B2;
3: @Override
4: protected void onCreate(Bundle savedInstanceState) {
5: super.onCreate(savedInstanceState);
6: setContentView(R.layout.activity_main);
7: B1 = (Button)findViewById(R.id.b1);
8: B2 = (Button)findViewById(R.id.b2);
9: B1.setOnClickListener(new OnClickListener() {
10: @Override
11: public void onClick(View arg0) {
12: FragmentManager FM = getFragmentManager();
13: FragmentTransaction FT = FM.beginTransaction();
14: FragmentOne F1 = new FragmentOne();
15: FT.add(R.id.fr1_id, F1);
16: FT.addToBackStack("f1");
17: FT.commit();
18: }
19: });
20: B2.setOnClickListener(new OnClickListener() {
21: @Override
22: public void onClick(View v) {
23: FragmentManager FM = getFragmentManager();
24: FragmentTransaction FT = FM.beginTransaction();
25: FragmentTwo F2 = new FragmentTwo();
26: FT.add(R.id.fr2_id, F2);
27: FT.addToBackStack("f2");
28: FT.commit();
29: }
30: });
31: }

FragmentOne.java
1:  public class FragmentOne extends Fragment{  
2: @Override
3: public View onCreateView(LayoutInflater inflater, ViewGroup container,
4: Bundle savedInstanceState) {
5: // TODO Auto-generated method stub
6: View v = inflater.inflate(R.layout.fragment_one_layout, container,false);
7: return v;
8: }
9: }

FragmentTwo.java
1:  public class FragmentTwo extends Fragment {  
2: @Override
3: public View onCreateView(LayoutInflater inflater, ViewGroup container,
4: Bundle savedInstanceState) {
5: // TODO Auto-generated method stub
6: View v = inflater.inflate(R.layout.fragment_two_layout, container,false);
7: return v;
8: }
9: }

fragments_in_android