Sunday 27 January 2013

Fragment Example in Android(2)

activity_main.xml:

<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_height="match_parent"
        android:layout_weight="1"
        android:background="#555555"
        android:text="It's TextView in main Activity"
        android:textColor="#ffccff"
        android:textSize="30dp" />

    <FrameLayout
        android:id="@+id/myfragment"
        android:layout_width="0px"
        android:layout_height="match_parent"
        android:layout_weight="4" >
    </FrameLayout>

</LinearLayout>

fragmentlayout.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" >

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="It's a Fragment" />

    <ImageView
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:src="@drawable/ic_launcher" />

</LinearLayout>

MyFragment.java:
package com.example.frag5;

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

@SuppressLint("NewApi")
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;
}

}


MainActivity.java:
package com.example.frag5;

import android.annotation.SuppressLint;
import android.app.FragmentTransaction;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;

public class MainActivity extends FragmentActivity {

@SuppressLint("NewApi")
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

FragmentTransaction fragmentTransaction = getFragmentManager()
.beginTransaction();

MyFragment myFragment = new MyFragment();

fragmentTransaction.add(R.id.myfragment, myFragment);

fragmentTransaction.commit();
}

}


1 comment:

  1. Works well, all code totally correct (rarity)

    ReplyDelete