Android开发之Fragment动态添加与管理

这篇具有很好参考价值的文章主要介绍了Android开发之Fragment动态添加与管理。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

主界面布局资源

activity_main.xml中,声明两个按钮备用,再加入一个帧布局,待会儿用来展示Fragment。

<?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">

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/button1"
        android:text="@string/push"/>
    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/button2"
        android:text="@string/replace"/>

    <FrameLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/framelayout"
        android:background="@color/purple_200"/>

</LinearLayout>

两个工具Fragment

用来展示的Fragment,随便找两个AS预设的即可,这里使用的是一个BlankFragment和一个ItemFragment。
BlankFragment:

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout 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"
    tools:context=".BlankFragment1">

    <!-- TODO: Update blank fragment layout -->
    <TextView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:text="@string/hello_blank_fragment" />

</FrameLayout>
package com.example.dynamicfragment;

import android.os.Bundle;

import androidx.fragment.app.Fragment;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link BlankFragment1#newInstance} factory method to
 * create an instance of this fragment.
 */
public class BlankFragment1 extends Fragment {

    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;

    public BlankFragment1() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment BlankFragment1.
     */
    // TODO: Rename and change types and number of parameters
    public static BlankFragment1 newInstance(String param1, String param2) {
        BlankFragment1 fragment = new BlankFragment1();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_blank1, container, false);
    }
}

ItemFragment:

<?xml version="1.0" encoding="utf-8"?>
<androidx.recyclerview.widget.RecyclerView 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:id="@+id/list"
    android:name="com.example.dynamicfragment.ItemFragment"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_marginLeft="16dp"
    android:layout_marginRight="16dp"
    app:layoutManager="LinearLayoutManager"
    tools:context=".ItemFragment"
    tools:listitem="@layout/fragment_item" />
package com.example.dynamicfragment;

import android.content.Context;
import android.os.Bundle;

import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.example.dynamicfragment.placeholder.PlaceholderContent;

/**
 * A fragment representing a list of Items.
 */
public class ItemFragment extends Fragment {

    // TODO: Customize parameter argument names
    private static final String ARG_COLUMN_COUNT = "column-count";
    // TODO: Customize parameters
    private int mColumnCount = 1;

    /**
     * Mandatory empty constructor for the fragment manager to instantiate the
     * fragment (e.g. upon screen orientation changes).
     */
    public ItemFragment() {
    }

    // TODO: Customize parameter initialization
    @SuppressWarnings("unused")
    public static ItemFragment newInstance(int columnCount) {
        ItemFragment fragment = new ItemFragment();
        Bundle args = new Bundle();
        args.putInt(ARG_COLUMN_COUNT, columnCount);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        if (getArguments() != null) {
            mColumnCount = getArguments().getInt(ARG_COLUMN_COUNT);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_item_list, container, false);

        // Set the adapter
        if (view instanceof RecyclerView) {
            Context context = view.getContext();
            RecyclerView recyclerView = (RecyclerView) view;
            if (mColumnCount <= 1) {
                recyclerView.setLayoutManager(new LinearLayoutManager(context));
            } else {
                recyclerView.setLayoutManager(new GridLayoutManager(context, mColumnCount));
            }
            recyclerView.setAdapter(new MyItemRecyclerViewAdapter(PlaceholderContent.ITEMS));
        }
        return view;
    }
}

主程序

在主程序里,我们要实现点击按钮显示不同的Fragment。这里使用一种新的实现按钮方式,在声明MainActivity类的时候引用View.OnClickListener接口,然后在button1.setOnClickListener(this);中传入this,这样按钮被点击时就会自动调用后面写的OnClick函数。

OnClick函数被调用时,我们判断是哪一个按钮被点击了,然后根据按钮ID将不同的Fragment展现在帧布局上。

package com.example.dynamicfragment;

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

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

    private void replaceFragment(Fragment fragment) {
        FragmentManager fragmentManager = getSupportFragmentManager();
        FragmentTransaction transaction = fragmentManager.beginTransaction();
        transaction.replace(R.id.framelayout, fragment);//创建replace事件
        transaction.addToBackStack(null);
        transaction.commit();//执行transaction中的事件
    }
}

还需要重点讲解一下的是replaceFragment函数中的栈,transaction.addToBackStack(null);中的null指代的是默认栈。加入该语句后,每次更新都会向栈中加入一个Fragment,且屏幕上显示的即是栈顶的Fragment。当我们点击返回按钮时,栈顶的Fragment被弹出,屏幕上显示下一个Fragment。

试验如下,交替点击两个按钮若干次,屏幕上会依次出现两个Fragment交替覆盖,而点击返回按钮后,最顶上Fragment则会被撤除。
Android开发之Fragment动态添加与管理,Android开发,android,android studio
Android开发之Fragment动态添加与管理,Android开发,android,android studio文章来源地址https://www.toymoban.com/news/detail-611928.html

到了这里,关于Android开发之Fragment动态添加与管理的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • Android Studio开发简易APP添加代办事项

    创建xml布局页

    2024年02月15日
    浏览(32)
  • Android Studio初学者实例:Fragment学习--仿美团外卖界面

    本次课程为Fragment为主题,课程的示例仿美团外卖界面,不同于底部导航栏的Fragment案例,此界面分为左侧切换与顶部切换。本文先是发布代码与效果,后续讲解将会在后续补充。先看看效果: 首先是布局文件代码:Activity布局:activity_main.xml: 首先父布局用的LinearLayout布局,

    2024年02月03日
    浏览(53)
  • android studio开发——android11版本以上权限动态申请问题,包括文件读写、图片、相机的调用

    用于android手机的升级,现在已经是android13版本了,对于权限问题可能更加敏感了,前段时间开发发现之前的方法已经不再适用于android11以后的版本了 读写权限申请最好是跳转到设置中进行才是最好了,下面我们开始进行 首先是AndroidManifest.xml文件的权限 然后这里讲解一下权

    2024年02月10日
    浏览(47)
  • 基于Android的学生信息管理App设计(Android studio开发)

    目 录 一、 题目选择(题目、选题意义) 3 二、 设计目的 3 1、 初衷 3 2、 结合实际 3 3、 使用工具 3 三、 最终页面效果展示 4 1、 登陆界面 4 2、 主界面 5 3、 各个功能模块 6 四、 各部分设计 11 1、活动页面Activity布局文件 11 2、Activity的编程 13 五、 总结 17 题目:基于Android的

    2024年02月08日
    浏览(86)
  • Android Studio开发图书管理系统APP

    Android Studio开发项目图书管理系统项目视频展示: 点击进入图书管理系统项目视频 现在是一个信息高度发达的时代,伴随着科技的进步,文化的汲取,人们对于图书信息的了解与掌握也达到了一定的高度。尤其是学生对于知识的渴求更是与日俱增。图书馆作为学生学习知识的

    2024年02月03日
    浏览(38)
  • 基于Android Studio开发的人员管理系统APP

    目录 人员管理系统 前言 一、系统的大概流程 二、详细开发步骤 1.登陆界面 2.中间跳转界面 3.添加用户 4.全部用户界面  5.项目下载 总结 这是一个具有登录功能和人员信息增删改查功能的人员管理系统,在之前也有做过一个通过http协议与云平台对接的app,正好需要完成一个

    2024年02月07日
    浏览(55)
  • 【安卓大作业】Android Studio开发项目图书管理系统“书香驿站”

    项目视频展示: Android安卓大作业图书管理系统 一、项目背景 随着移动终端使用率的快速增加,Android智能产品已日益成为越来越多的人们选择的移动终端产品。伴随着Android智能手机与平板电脑已经在我们生活大量的使用,越来越多的基于Android开发平台的应用也随之产生。为

    2024年02月11日
    浏览(33)
  • Android Studio开发之使用内容组件Content获取通讯信息讲解及实战(附源码 包括添加手机联系人和发短信)

    运行有问题或需要源码请点赞关注收藏后评论区留言 在实际开发中,普通App很少会开放数据接口给其他应用访问。内容组件能够派上用场的情况往往是App想要访问系统应用的通讯数据,比如查看联系人,短信,通话记录等等,以及对这些通讯数据及逆行增删改查。 首先要给

    2024年02月09日
    浏览(51)
  • Android Studio 如何添加依赖

    1.有时候写项目需要添加一个依赖,比如我需要使用蓝牙,但是又不想自己写,从网上找一个成熟稳定的蓝牙项目,在自己的项目中添加一个文件夹取个名字,再把找到的项目中app路径下的内容, 把这些复制到自己项目的新建文件夹中,这样就成了一个内部模块,然后再将此

    2024年02月12日
    浏览(38)
  • Android Studio App开发之通知渠道NotificationChannel及给华为、小米手机桌面应用添加消息数量角标实战(包括消息重要级别的设置 附源码)

    需要全部源码或运行有问题请点赞关注收藏后评论区留言~~~ 为了分清消息通知的轻重缓急,Android8.0新增了通知渠道,并且必须指定通知渠道才能正常推送消息,一个应用允许拥有多个通知渠道,每个渠道的重要性各不相同,有的渠道消息在通知栏被折叠成小行,有的渠道消

    2024年02月16日
    浏览(44)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包