activity_main.xml:
<RelativeLayout 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:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" android:id="@+id/rl_fragment_id" tools:context=".MainActivity" > </RelativeLayout>
layout.xml一个fragment的填充布局:
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:background="#00f" android:orientation="vertical" > </LinearLayout>
MainActivity.java
package com.qf.day14_fragment_demo08_v4; import com.qf.day14_fragment_demo08_v4.fragment.MyFragment; import android.os.Bundle; import android.app.Activity; import android.support.v4.app.FragmentActivity; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentTransaction; import android.view.Menu; /** * 1,创建一个类 继承V4包的Fragment * 2,修改Activity 变成FragmentActivity * 3,获取管理者对象 V4 getSupportFragmentManager() 获取事务 V4 * @author sxy * */ public class MainActivity extends FragmentActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); //获取Fragment的管理者 FragmentManager manager = getSupportFragmentManager(); //事务 FragmentTransaction transaction = manager.beginTransaction(); transaction.replace(R.id.rl_fragment_id, new MyFragment()); transaction.commit(); } }
fragment对象:
package com.qf.day14_fragment_demo08_v4.fragment; import com.qf.day14_fragment_demo08_v4.R; import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; public class MyFragment extends Fragment { @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // TODO Auto-generated method stub View view = inflater.inflate(R.layout.layout, container, false); return view; } }