Fragment 的靜態加載

使用android-support-v4.jar包,在使用與Fragment相關的Api時,必須用android-support-v4包中的,其能安裝到低版本(1.6)的手機;java

一:靜態加載Fragmentandroid

  1:Activity必須繼承v4包的 FragmentActivity ;ide

  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佈局xml

<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
 * 1、定義Fragment子類並加載佈局
 * 2、在佈局文件中指定自定義的Fragment
 * 3、父Activity必須繼承FragmentActivity
 * 每一個Fragemt本質上都會生成一個FrameLayout,他加載的佈局爲其子佈局
 * 
 * */
public class MainActivity extends FragmentActivity {

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
	}
}
相關文章
相關標籤/搜索