
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>
Add a new class MyFragment extends Fragment.
package com.exercise.FragmentTest;
import android.app.Fragment;
import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;
public class MyFragment extends Fragment {
 @Override
 public View onCreateView(LayoutInflater inflater, ViewGroup container,
   Bundle savedInstanceState) {
  // TODO Auto-generated method stub
  Context context = getActivity().getApplicationContext();
  LinearLayout layout = new LinearLayout(context);
  TextView text = new TextView(context);
  text.setText("It's Fragment");
  layout.addView(text);
  
  return layout;
 }
}
Modify the main activity to add our MyFragment.
package com.exercise.FragmentTest;
import android.app.Activity;
import android.app.Fragment;
import android.os.Bundle;
public class FragmentTestActivity extends Activity{
 
 Fragment fragment;
 
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
    }
}
No comments:
Post a Comment