Android基础:Fragment

本文详细介绍了Android中的Fragment,包括它的生命周期、基本使用方法、如何动态添加和管理Fragment,以及Fragment与Activity之间的通信。通过实例展示了Fragment的创建和在Activity中的引入,同时提供了动态替换Fragment的代码示例。此外,还探讨了使用Bundle进行参数传递的原生通信方案。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

介绍

        Fragment是Android3.0后引入的一个新的API,主要是为了大屏应运而生的。Fragment是一个事务,我们可以把它看做一个小型的Activity。Fragment可以将一个屏幕划分为多块,然后重组,使我们很方便的对这些小块进行模块化管理,从而更加方便的动态更新布局页面。
        Fragment是不能单独使用的,必须依托在Activity中使用,Fragment有自己的生命周期,但是因为以上缘故,所以他的生命周期也会受到Activity影响,当Activity被销毁了,Fragment也会被销毁。

生命周期

请添加图片描述

使用方法

  1. 写一个Fragment和对应的Layout。
<!-- fragment_first.xml -->
<?xml version="1.0" encoding="utf-8"?>
<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=".firstFragment">

    <TextView
        android:id="@+id/tView_one"
        android:layout_width="match_parent"
        android:layout_height="40dp"
        android:layout_marginBottom="4dp"
        android:text="@string/hello_blank_fragment"
        />

    <Button
        android:id="@+id/button_one"
        android:layout_width="match_parent"
        android:layout_height="40dp"
        android:text="how are you?" />
</LinearLayout>
public class firstFragment extends Fragment {

	    private View root;
	    private TextView textView;
	    private Button button;
	
	    @Override
	    public void onCreate(Bundle savedInstanceState) {
	        super.onCreate(savedInstanceState);
	
	    }
	
	    @Override
	    public View onCreateView(LayoutInflater inflater, ViewGroup container,
	                             Bundle savedInstanceState) {
	
	        if(root==null){
	            root = inflater.inflate(R.layout.fragment_first, container, false);
	        }
	        
	        textView = root.findViewById(R.id.tView_one);
	        button = root.findViewById(R.id.button_one);
	
	        button.setOnClickListener(new View.OnClickListener(){
	            @Override
	            public void onClick(View view) {
	                textView.setText("Yes,I am fine,thinks");
	            }
	        });
	        return root;
	    }
}
  1. 在Activity中引入fragment.
    注意:其中fragment必须要有ID,因为fragment管理中必须要用ID管理。
    name引用对应的fragment。
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity">

    <fragment
        android:layout_width="match_parent"
        android:layout_height="match_parent"
	android:name="com.example.fragmentstudy.firstFragment"
        android:id="@+id/fragment_one"
        />
</LinearLayout>

动态添加和管理Fragment

  1. 创建一个待处理的Fragment
  2. 获取FragmentManager,一般都是通过getSupportFragmentManager()
  3. 开启一个事务transaction, 一般是调用FragmentManager的beginTransaction()
  4. 使用transaction进行fragment的替换。
  5. 将fragment加入back栈。
    将操作加入back栈中,在点击返回键的时候,就会按照出栈顺序一个页面一个页面返回。(非必须)
 public FragmentTransaction addToBackStack(@Nullable String name);
  1. 提交事务

详细代码

// MainActivity.java
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;

import android.os.Bundle;
import android.view.View;
import android.widget.Button;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button button = findViewById(R.id.button_one);
        button.setOnClickListener(this);
        Button button2 = findViewById(R.id.button_two);
        button2.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.button_one:
                replaceFragment(new FirstFragment());
                break;
            case R.id.button_two:
                replaceFragment(new ItemFragment());
                break;
        }
    }

    private void replaceFragment(Fragment fragment) {
        /**
         * 这是用来专门用来管理fragment的
         * getSupportFragmentManager可以获取默认的fragment管理类
         */
        FragmentManager fragmentManager = getSupportFragmentManager();
        // 得到一个Transaction
        FragmentTransaction transaction = fragmentManager.beginTransaction();
        /**
         * 然后做替换
         * 将fragment 替换到 id为fragment_one上来。
         */
        transaction.replace(R.id.fragment_one,fragment);

        /**
         * 入返回栈
         * 每次操作都加入栈中,然后如果点返回键,就会从栈里面一个一个退出
         */
        transaction.addToBackStack("fragment");
        // 事务提交
        transaction.commit();
    }
}

在这里插入图片描述

Fragment和Activity通信

        Fragment和Activity是相互独立的类,他们之中怎么通信。
        1. Fragment 向Activity通信。
        2. Activity向Fragment 通信。
        3. Fragment 向Fragment 通信。

原生方案(Bundle)

        安卓提供的原生方案是Bundle,可以支持上面的通信。
        放入参数。
在这里插入图片描述
        获取参数。在create之后就可以获取。
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值