一.首先将fragment准备好
包含两部分,一部分是布局文件,一部分是类
1.布局文件:普通的布局文件就行
<?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="#afc"
android:orientation="vertical">
<Button
android:id="@+id/bt_left"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:text="按钮" />
</LinearLayout>
2.类:在类中引入布局文件
package com.example.administrator.fragment;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class LeftFragment extends Fragment {
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.left_fragment, container);
return view;
}
}
二,activity里添加fragment
包含两部分,一部分是在activity布局文件中给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:orientation="horizontal">
<FrameLayout
android:id="@+id/left"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"></FrameLayout>
</LinearLayout>
那个FrameLayout就是将来被替换为fragment的对象
然后再在activity代码中动态添加fragment
FragmentManager mannager = getSupportFragmentManager();
FragmentTransaction tronsaction = mannager.beginTransaction();
tronsaction.replace(R.id.left, 要替换的fragment);
tronsaction.addToBackStack(null);
tronsaction.commit();