1.新建Fragment的XML布局文件。
2.在activity.xml中添加需要加载Fragment。列如:
1 <?xml version="1.0" encoding="utf-8"?> 2 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 3 xmlns:tools="http://schemas.android.com/tools" 4 android:layout_width="match_parent" 5 android:layout_height="match_parent" 6 android:orientation="vertical" 7 tools:context="com.example.administrator.fragment_01.activity.MainActivity"> 8 9 <FrameLayout 10 android:id="@+id/fragment_id" 11 android:layout_width="match_parent" 12 android:layout_height="0dp" 13 android:layout_weight="1" /> 14 15 <LinearLayout 16 android:id="@+id/layout_1" 17 android:layout_width="match_parent" 18 android:layout_height="wrap_content" 19 android:gravity="bottom" 20 android:orientation="horizontal"> 21 22 <Button 23 android:id="@+id/activity_button_1" 24 android:layout_width="0dp" 25 android:layout_height="wrap_content" 26 android:layout_weight="1" 27 android:text="@string/button_1" /> 28 29 <Button 30 android:id="@+id/activity_button_2" 31 android:layout_width="0dp" 32 android:layout_height="wrap_content" 33 android:layout_weight="1" 34 android:text="@string/button_2" /> 35 36 </LinearLayout> 37 </LinearLayout>
3.创建MyFragment类继承Fragment类。
1 public class MyFragment extends Fragment { 2 3 @Override 4 public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { 5 View view = inflater.inflate(R.layout.one_fragment, container,false); 6 return view; 7 } 8 }
4.创建待添加Fragment的实例。
5.获取FragmentManager。
6.开启一个事务。
7.向容器中添加或替换碎。
8.提交事务。
1 public class MainActivity extends AppCompatActivity implements View.OnClickListener { 2 3 private Button button; 4 private Button button1; 5 6 @Override 7 protected void onCreate(Bundle savedInstanceState) { 8 super.onCreate(savedInstanceState); 9 setContentView(R.layout.activity_main); 10 Button button = (Button) findViewById(R.id.activity_button_1); 11 Button button1 = (Button) findViewById(R.id.activity_button_2); 12 button.setOnClickListener(this); 13 button1.setOnClickListener(this);
//创建实例做参数穿入。 14 replaceFragment(new MyFragment()); 15 } 16 17 18 @Override 19 public void onClick(View view) { 20 21 switch (view.getId()) { 22 case R.id.activity_button_1: 23 replaceFragment(new MyFragment_2()); 24 Toast.makeText(this, "点击了第一个", Toast.LENGTH_SHORT).show(); 25 break; 26 case R.id.activity_button_2: 27 replaceFragment(new MyFragment()); 28 Toast.makeText(this, "点击了第二个", Toast.LENGTH_SHORT).show(); 29 break; 30 } 31 } 32 33 private void replaceFragment(Fragment fragment) { 34 35 //2.获取FragmentManager. 36 FragmentManager fragmentManager = getSupportFragmentManager(); 37 //3.开启一个事务beginTransaction() 38 FragmentTransaction transaction = fragmentManager.beginTransaction(); 39 //向容器中添加或替换碎片 40 transaction.replace(R.id.fragment_id, fragment); 41 //提交事务 42 transaction.commit(); 43 } 44 }