Fragment的创建和使用

一、Fragment添加至Activity

  • 由于 Fragment 作为 Activity 一部分,所以 Fragment 的使用一般是添加到Activity
  • Fragment 添加到 Activity 中一般有2种方法:
  1. Activitylayout.xml 布局文件中静态添加
  2. Activity.java 文件中动态添加
方法 1:在 Activitylayout.xml 布局中静态添加
  • Fragment 的布局文件
    fragment_test.xml
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:gravity="center"
        android:orientation="vertical">
    
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="测试Fragment" />
    
    </LinearLayout>
    
  • Fragment.java 文件
    要创建 Fragment,应该继承 Fragment 类,然后替换关键生命周期方法插入应用逻辑,创建方式类似于 Activity 类。创建 Fragment 时一个区别是我们必须使用 onCreateView() 回调定义布局。
    ExampleFragment.java
     import androidx.fragment.app.Fragment;
     public class ExampleFragment extends Fragment{
        @Override
         public View onCreateView(LayoutInflater inflater, ViewGroup container,
                               Bundle savedInstanceState) {
            // Inflate the layout for this fragment
             return inflater.inflate(R.layout.fragment_test, container, false);
      }
    }
    
  • Activity 的布局文件
    activity_statically_add_fragment.xml
    <?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">
    
      <fragment
          android:id="@+id/fragment"
          android:name="com.xyz.fragment.activity.ExampleFragment"
          android:layout_width="match_parent"
          android:layout_height="match_parent" />
    
    </LinearLayout>
    
  • Activity.java 文件
    StaticallyAddFragmentActivity.java
    public class StaticallyAddFragmentActivity extends AppCompatActivity{
      @Override
      protected void onCreate(Bundle savedInstanceState) {
          super.onCreate(savedInstanceState);
          setContentView(R.layout.activity_statically_add_fragment);
      }
    }
    
方法 2:在运行时为Activity添加Fragment

要执行添加或移除Fragment等事务,必须使用FragmentManager创建一个FragmentTransaction,后者将提供添加、移除、替换Fragment以及执行其他Fragment事务所需的API
如果Activity允许移除和替换Fragment,应在ActivityonCreate() 方法执行期间为其添加初始Fragment

  • 设置 Fragment 的布局文件
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
      android:layout_width="match_parent"
      android:layout_height="match_parent"
      android:gravity="center"
      android:orientation="vertical">
    
      <TextView
          android:layout_width="wrap_content"
          android:layout_height="wrap_content"
          android:text="测试Fragment" />
    
    </LinearLayout>
    
  • Fragement 的代码
    public class ExampleFragment extends Fragment{
      @Override
      public View onCreateView(LayoutInflater inflater, ViewGroup container,
                               Bundle savedInstanceState) {
          return inflater.inflate(R.layout.fragment_test, container, false);
    
      }
    }
    
  • Activity 的布局文件中定义1占位容器(FrameLayout)
    可以动态在Activity中添加不同的Fragment
    <?xml version="1.0" encoding="utf-8"?>
       <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/fragment"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />
    
  • Activity.java文件动态添加 Fragment
    public class DynamicAddFragmentActivity extends BaseActivity {
      @Override
      protected void onCreate(@Nullable Bundle savedInstanceState) {
          super.onCreate(savedInstanceState);
          setContentView(R.layout.activity_dynamic_add_fragment);
    
          //1. 获取FragmentManager
          FragmentManager fragmentManager = getSupportFragmentManager();
    
          //2. 获取FragmentTransaction
          FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
    
          //3. 创建需要添加的Fragment
          ExampleFragment fragment = new ExampleFragment();
    
          //4. 动态添加Fragment(即将创建的fragment添加到Activity布局文件中定义的FrameLayout)
          fragmentTransaction.add(R.id.fragment, fragment);
    
          fragmentTransaction.commit();
      }
    }
    

注:FragmentActivity 是支持库中提供的特殊 Activity,用于处理早于API级别11的系统版本上的Fragment。 如果使用V7 appompat库,那么Activity应继承AppCompatActivity,它是FragmentActivity的子类。

二、替换Fragment

替换Fragment的过程与动态添加Fragment类似,但需要调用replace()方法,而非add()
需要注意的是,当执行替换或移除FragmentFragment事务时,通常最好让用户能够回退并“撤销”更改。要让用户回退所执行的Fragment事务,我们必须先调用addToBackStack(),然后再提交FragmentTransaction

注意:当我们移除或替换Fragment并向返回堆栈添加相应事务时,系统会停止(而非销毁)移除的Fragment。如果用户执行回退操作进行Fragment恢复,该Fragment将重新启动。如果不向返回堆栈添加相应事务,则系统会在移除或替换Fragment时将其销毁。

    // Create fragment and give it an argument specifying the article it should show
    ArticleFragment newFragment = new ArticleFragment();
    Bundle args = new Bundle();
    args.putInt(ArticleFragment.ARG_POSITION, position);
    newFragment.setArguments(args);

    FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();

    // Replace whatever is in the fragment_container view with this fragment,
    // and add the transaction to the back stack so the user can navigate back
    transaction.replace(R.id.fragment_container, newFragment);
    transaction.addToBackStack(null);

    // Commit the transaction
    transaction.commit();

addToBackStack()方法采用一个可选的字符串参数,该参数会为事务指定一个唯一的名称。

三、资源

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值