Fragment业务场景来说,一定程度等于vue的component,而路由对应的vue文件类同安卓的activity。
vue即使页面也可以做组件被另外个页面组件使用。但是Acitivity不能,android 里面fragment和Acitivity是严格区分的,是用不同的类实现的,生命周期也不大一样。

安卓里面的Fragment的使用更加显得古板,需要像jquery添加dom一样追加,显示和隐藏
Fragment的创建方式与Activity几乎一样,只是创建时候选择的是Fragment. AndroidStudio创建Fragment时候会创建布局文件和java类
Java类会在onCreateView方法里面自动绑定布局文件&&返回view类实例
代码如下:
- @Override
-
- public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
-
- View view = inflater.inflate(R.layout.fragment_my,container,false);
-
- TextView txt_content = (TextView) view.findViewById(R.id.txt_content);
-
- txt_content.setText(content);
-
- return view;
-
- }
也可以给Fragment的构造函数添加参数,以便在Acitvity实例该类的时候传递数据
例如:
- private String content;
-
- public MyFragment(String content) {
-
- this.content = content;
-
- }
整个代码如下:
- package com.example.fragmenttab;
-
-
-
- import android.os.Bundle;
-
-
-
- import androidx.fragment.app.Fragment;
-
-
-
- import android.view.LayoutInflater;
-
- import android.view.View;
-
- import android.view.ViewGroup;
-
- import android.widget.TextView;
-
-
-
- /**
-
- * A simple {@link Fragment} subclass.
-
- * Use the {@link MyFragment#newInstance} factory method to
-
- * create an instance of this fragment.
-
- */
-
- public class MyFragment extends Fragment {
-
-
-
- private String content;
-
- public MyFragment(String content) {
-
- this.content = content;
-
- }
-
-
-
- @Override
-
- public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
-
- View view = inflater.inflate(R.layout.fragment_my,container,false);
-
- TextView txt_content = (TextView) view.findViewById(R.id.txt_content);
-
- txt_content.setText(content);
-
- return view;
-
- }
-
- }
Activy消费该Fragment的时候,用vue的说法就是挂载该组件,Activy内部维护给变量来存储管理fragment的对象
private FragmentManager fManager;
在onCreate的生命周期给fManager赋值
- @Override
-
- protected void onCreate(Bundle savedInstanceState) {
-
- super.onCreate(savedInstanceState);
-
- //赋值
-
- fManager = getSupportFragmentManager();
-
- }
赋值后,我们就可以在其他方法添加,显示,隐藏,某些Fragment了。
对当前Activity的Fragment进行添加,显示,隐藏,移除的操作,可以无限次的读取事务,得到的都是对当前Activity的Fragment的事务对象。FragmentTransaction只能使用一次,每次使用都要调用FragmentManager 的beginTransaction()方法获得FragmentTransaction事务对象哦!
FragmentTransaction fTransaction = fManager.beginTransaction();
不过,这里先记录下如何实例一个Fragment,如果Fragment类名为MyFragment,就需要先实例,然后通过getSupportFragmentManager()的add方法添加到1⃣️Activity的xml布局文件上,add的第一个参数是xml某个Fragment的id,第二个参数是Fragment实例代码如下:
- MyFragment fg1 = new MyFragment("第一个Fragment");
-
- fTransaction.add(R.id.ly_content,fg1);
上面代码可以看到,实例的时候我们给MyFragment类传递了个字符串参数
1⃣️对于的xml代码如下
- <FrameLayout
-
- android:layout_width="match_parent"
-
- android:layout_height="match_parent"
-
- android:id="@+id/ly_content">
-
-
-
- </FrameLayout>
显示已隐藏的Fragment
fTransaction.show(fg1);
if(fg1 != null)fragmentTransaction.hide(fg1);
注意需要判空,否则可能会报错
FragmentManager是 androidx.fragment.app(已弃用的不考虑)下的抽象类,创建用于 添加,移除,替换 fragment 的事务(transaction)
该用getSupportFragmentManager替代