通过进出栈方式来对Fragment进行添加、移除

本文主要通过堆栈的方式来实现Fragment的添加与移除
首先我们创建一个Fragment的布局,放一个TextView进去




    

创建Fragment文件继承于Fragment

package com.game.broadcast;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

public class Fragment extends androidx.fragment.app.Fragment {
    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment,container,false);
return view;
    }
}

在Main布局中添加Fragment,放入两个按钮





    

        

接着在MainActivity中使用堆栈进行fragment的增减

package com.game.broadcast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import java.util.Stack;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    TextView textView;
    Button button1;
    Button button2;
    FragmentManager fragmentManager;
    //创建fragment的堆栈用于存放、删减
    Stack<Fragment>fragments=new Stack<Fragment>();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        button1=(Button)findViewById(R.id.button);
        button2=(Button)findViewById(R.id.button2);
        button1.setText("add");
        button2.setText("remove");
        button1= (Button)findViewById(R.id.button);
        button2 = (Button)findViewById(R.id.button2);
        button1.setOnClickListener(this);
        button2.setOnClickListener(this);
}

    @Override
    public void onClick(View view) {

        Fragment fragment = new Fragment();
        FragmentManager fragmentManager =getSupportFragmentManager();
        FragmentTransaction fragmentTransaction=fragmentManager.beginTransaction();
        switch(view.getId()){
            case R.id.button:
                fragmentTransaction.add(R.id.fragment,fragment);
                //将添加的fragment通过push放入堆栈
                this.fragments.push(fragment);
                fragmentTransaction.commit();
                break;
            case R.id.button2:
                //通过empty来判断堆栈是否为空,如果不为空则可以进行点击删掉fragment
                if(!this.fragments.empty())
                    //pop移除出栈
                fragmentTransaction.remove(this.fragments.pop());
                fragmentTransaction.commit();
                break;
                default:
                    break;
        }

    }
}

这里用到push将fragment加入堆栈中去,用pop出栈
用empty进行判定
根据empty的源码可以看出是一个boolean类型的,值应当是true或者false,

public boolean empty() {
        throw new RuntimeException("Stub!");
    }

因此在这里我们判断是否为空栈时也可以将代码写作
在这里插入图片描述
false即为不空,可以移除fragment,true则为空了。

你可能感兴趣的:(安卓开发)