Fragment 的静态加载

使用android-support-v4.jar包,在使用与Fragment相关的Api时,必须用android-support-v4包中的,其能安装到低版本(1.6)的手机;

一:静态加载Fragment

  1:Activity必须继承v4包的 FragmentActivity ;

  2:定义Fragement子类,并加载布局;

public class MyFragment1 extends Fragment {
	/**加载布局得到View并返回*/
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {         //加载布局并返回视图
		// TODO Auto-generated method stub
		//创建一个视图对象
		TextView textview = new TextView(getActivity());
		textview.setText("fragment111111");
		textview.setBackgroundColor(Color.RED);
		return textview;
	}
	
}

  3:在主布局文件中放入Fragment布局

<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"
    android:orientation="horizontal">

    <fragment
        android:id="@+id/fragment1"
        android:name="com.example.fragementdemo.MyFragment1"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_weight="1" />
</LinearLayout>

  4:贴上主Activity代码:

/**静态加载Fragement
 * 一、定义Fragment子类并加载布局
 * 二、在布局文件中指定自定义的Fragment
 * 三、父Activity必须继承FragmentActivity
 * 每个Fragemt本质上都会生成一个FrameLayout,他加载的布局为其子布局
 * 
 * */
public class MainActivity extends FragmentActivity {

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

  

  

原文地址:https://www.cnblogs.com/suliang-com/p/6389367.html