import android.os.Bundle; import android.support.v4.app.FragmentActivity; import android.util.Log; /* * 测试使用Fragment(静态加载) * 1. 定义Fragment的子类, 并加载一个布局文件 * 2. 在布局文件中通过<fragment>指定指定自定义Fragment * 3. 我们的Activity必须继承于FragmentActivity * 每个Fragment本质上都会生成一个FrameLayout, 它加载的布局为其子布局 */ public class MainActivity extends FragmentActivity { public MainActivity() { Log.e("TAG", "MainActivity().."); } @Override protected void onCreate(Bundle savedInstanceState) { Log.e("TAG", "MainActivity onCreate().."); super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } }
public class MyFragment1 extends Fragment { @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { //加载布局得到View对象并返回 //创建一个视图对象, 设置数据并返回 TextView textView = new TextView(getActivity()); textView.setText("fragment11111"); textView.setBackgroundColor(Color.RED); return textView; } } public class MyFragment2 extends Fragment { @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { //加载布局得到View对象并返回 //创建一个视图对象, 设置数据并返回 TextView textView = new TextView(getActivity()); textView.setText("fragment22222"); return textView; } }
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"> <fragment android:name="com.example.l12_fragment1.MyFragment1" android:layout_width="0dp" android:layout_weight="1" android:layout_height="match_parent" /> <fragment android:name="com.example.l12_fragment1.MyFragment2" android:layout_width="0dp" android:layout_weight="1" android:layout_height="match_parent" /> </LinearLayout>