【Android】Fragment

本文介绍了Fragment的基本概念,包括其生命周期管理、在Activity中的创建与动态添加,以及Fragment与Activity之间的通信方式,如Bundle和接口回调。还探讨了Fragment在实际项目中的应用场景和生命周期管理策略。
摘要由CSDN通过智能技术生成

一、什么是Fragment
1.具备生命周期
2.必须委托在activity才能运行
二、Fragment的初创建
1.activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<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:name="com.example.test_three.BlankFragment1"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_weight="1"
        android:id="@+id/fragment1"/>

    <fragment
        android:name="com.example.test_three.BlankFragment2"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_weight="1"
        android:id="@+id/fragment2"/>

</LinearLayout>

2.BlankFragment1

public class BlankFragment1 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_blank1, container, false);
        }
        textview = root.findViewById(R.id.textview);
        button = root.findViewById(R.id.btn);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                textview.setText("Yes,I am are you");
            }
        });
        return root;
    }
}

三、Fragment动态添加与管理
1)创建一个待处理的fragment
2)获取FragmentManager,一般都是通过getSupportFragmentManager()
3)开启一个事务transaction,一般调用fragmentManager的beginTransaction()
4)使用transaction进行fragment的替换
5)提交事务

1.创建两个Fragment,一个black和一个list。需要引入这个包下的Fragment
在这里插入图片描述
2.mainActivity

package com.example.myapplication;

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.btn);
        button.setOnClickListener(this);
        Button button2 = findViewById(R.id.btn2);
        button2.setOnClickListener(this);
    }


    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.btn:
                replaceFragment(new BlankFragment1());
                break;
            case R.id.btn2:
                replaceFragment(new ItemFragment());
                break;
        }
    }

    //完成动态切换fragment
    private void replaceFragment(Fragment fragment) {
        FragmentManager fragmentManager = getSupportFragmentManager(); // 获取管理类
        FragmentTransaction transation = fragmentManager.beginTransaction();
        transation.replace(R.id.framelayout,fragment);
        transation.addToBackStack(null);
        transation.commit();
    }
}

四、Fragment和Activity通信
1)Bundle
1.MainActivity

    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.btn:
                Bundle bundle = new Bundle();
                bundle.putString("message","无喜欢享学课堂");
                BlankFragment1 bf = new BlankFragment1();
                bf.setArguments(bundle);
                replaceFragment(bf);
                break;
            case R.id.btn2:
                replaceFragment(new ItemFragment());
                break;
        }
    }

2.BlankFragment1

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Bundle bundle = getArguments();
        String string = bundle.getString("messae");
        Log.d(TAG,"onCreate:" + string);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }

2)接口
1.先在BlankFragment 中添加一个button

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:id="@+id/btn3"
        android:text="数据传递"/>

2.创建一个接口 叫IFragmentCallback

package com.example.myapplication;

public interface IFragmentCallback {
    void  sendMsgToActivity(String string);
    String getMsgFromActivity(String msg);
}

3.在BlankFragment中创建set方法

    private IFragmentCallback fragmentCallback;
    public void setFragmentCallback(IFragmentCallback callback){
        fragmentCallback = callback;
    }

5.添加事件

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        if(rootview == null){
            rootview = inflater.inflate(R.layout.fragment_blank1,container,false);
        }
        Button btn = rootview.findViewById(R.id.btn3);
        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
//                fragmentCallback.sendMsgToActivity("hello ,I`m from Fragment");
                String msg = fragmentCallback.getMsgFromActivity(null);
                Toast.makeText(BlankFragment1.this.getContext(),msg,Toast.LENGTH_SHORT).show();
            }
        });

        return rootview;
    }

6.Main中书写匿名内部类

    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.btn:
                Bundle bundle = new Bundle();
                bundle.putString("message","无喜欢享学课堂");
                BlankFragment1 bf = new BlankFragment1();
                bf.setArguments(bundle);
                bf.setFragmentCallback(new IFragmentCallback() {
                    @Override
                    public void sendMsgToActivity(String string) {
                        Toast.makeText(MainActivity.this,string,Toast.LENGTH_SHORT).show();;
                    }

                    @Override
                    public String getMsgFromActivity(String msg) {
                        return "I am from activity";
                    }
                });
                replaceFragment(bf);
                break;
            case R.id.btn2:
                replaceFragment(new ItemFragment());
                break;
        }
    }

3)观察者,发布订阅
eventBus,LiveData…

五、生命周期
在这里插入图片描述
在这里插入图片描述
如果需要状态清零在OnPause()中
这个是不存入栈中的 也就是addTpBackStack(null);
如果存入栈中,在替换时,会多一个onDestroyView

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值