Fragment的基本使用
一. Fragment 的常用方法
方法 | 介绍 |
---|---|
add() | 添加Fragment |
replace | 替换Fragment |
remove() | 移除Fragment |
hide() | 隐藏Fragment |
show() | 显示Fragment |
二. Fragment 的使用
- 为将要创建的Fragment准备布局一个布局: layout_fragment
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#345467">
<TextView
android:id="@+id/textView_id"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="这是MyFragment的布局"
android:textColor="#ffffff"
android:textSize="18sp"/>
</LinearLayout>
- 创建一个类MyFragment 继承Fragment, 并重写onCreateView方法:
public class MyFragment extends Fragment { //继承Fragment
@Nullable //注释 可为空
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View root = inflater.inflate(R.layout.layout_fragment, container, false);
return root;
}
}
- MainActivity 主界面, onCreate中
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// 获取Fragment管理类
FragmentManager fm = getSupportFragmentManager();
// 进行本次管理(每次管理需要重新获得) transaction: 事务, 办理
FragmentTransaction transaction = fm.beginTransaction();
// 添加Fragment 参数1: 主布局中的容器, 参数2: fragment对象, 参数3: 别名
transaction.add(R.id.frame_home, new MyFragment(), "f1");
// 其他方法
// transaction.replace(主布局中的容器, fragment对象);
// transaction.remove(frament对象);
// transaction.hide(frament对象);
// transaction.show(frament对象);
transaction.commit(); //开始执行
}
}
- 主布局的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="vertical"
tools:context=".MainActivity">
<FrameLayout
android:id="@+id/frame_home"
android:layout_width="300dp"
android:layout_height="200dp">
</FrameLayout>
</LinearLayout>
效果图如下: