草庐IT

Fragment的四种跳转方式

SY_XLR 2023-07-11 原文

本文主要记录了关于fragment的四种跳转方式:  

1、从同一个Activiy的一个Fragment跳转到另外一个Fragment  
2、从一个Activity的Fragment跳转到另外一个Activity  
3、从一个Activity跳转到另外一个Activity的Fragment上
4、从一个Activity的Fragment跳转到另外一个Activity的Fragment上

写这篇文章只是一个简单的记录,当初我学这里的时候看别人的文章总是觉得云里雾里的,后来自己也觉得差不多可以了,于是写下这篇博客,也是记录自己的学习过程。

首先新建一个项目,然后新建两个活动MainActivity、OtherActivity。
在MainActivity的布局文件中写一个子布局:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">


    <FrameLayout
        android:id="@+id/fragment_container"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"/>


</LinearLayout>

新建一个my_fragment.xml布局与MyFragment类

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="MyFragment"
        android:textSize="40sp"
        android:gravity="center_horizontal"/>

    <Button
        android:id="@+id/my_button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAllCaps="false"
        android:text="To YourFragment"/>

    <Button
        android:id="@+id/my_other"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAllCaps="false"
        android:text="To OtherActivity"/>

</LinearLayout>

MyFragment类就暂时省略了,后面会贴出所有代码。
在MainActivity中先添加进一个Fragment进行最开始的展示(压栈式添加)

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        getSupportFragmentManager()
                .beginTransaction()
                .replace(R.id.fragment_container,new MyFragment())
                .addToBackStack(null)
                .commit();

    }
}

从同一个Activiy的一个Fragment跳转到另外一个Fragment

这个跳转与上面初始显示Fragment类似。
新建your_fragment.xml布局与YourFragment类。

public class YourFragment extends Fragment {
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View contentView;
        contentView = inflater.inflate(R.layout.your_fragment, container, false);
        return contentView;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        Button myReturn = (Button) getActivity().findViewById(R.id.my_return);
        myReturn.setOnClickListener(new View.OnClickListener() {
            //返回到上一个Fragment(同一个Activity中)
            @Override
            public void onClick(View v) {
                getActivity().getSupportFragmentManager().popBackStack();
            }
        });
    }
}

your_fragment.xml就暂时先省略了,最后会贴出全部代码。

跳转部分代码如下,通过点击按钮跳转:

myButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                /** 一、从同一个Activity的一个Fragment跳到另外一个Fragment*/
                //压栈式跳转
                getActivity().getSupportFragmentManager()
                        .beginTransaction()
                        .replace(R.id.fragment_container, new YourFragment(), null)
                        .addToBackStack(null)
                        .commit();

            }
        });

从一个Activity的Fragment跳转到另外一个Activity

此跳转与Activity之间的跳转十分相似,只要引用上下文的时候,改成getActivity()即可。

跳转关键代码:

myOther.setOnClickListener(new View.OnClickListener() {
            /**
             二、从一个Activity的Fragment跳转到另外一个Activity(等同于Activity之间的跳转(上下文是getActivity))
             */
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getActivity(),OtherActivity.class);
                startActivity(intent);
            }
        });

从一个Activity跳转到另外一个Activity的Fragment上

我们要从OtherActivity跳转到MainActivity的YourFragment上去:
首先,我们在OtherActivity中的跳转事件中给MainActivity传递一个参数,命名为id:

Intent intent = new Intent(OtherActivity.this, MainActivity.class);
intent.putExtra("id",1);
startActivity(intent);

 然后,我们在MainActivity里接收id值,对值进行判断,如果正确进行跳转操作:

int id = getIntent().getIntExtra("id", 0);
if (id == 1) {      
     getSupportFragmentManager()
       .beginTransaction()
       .replace(R.id.fragment_container,new YourFragment())
       .addToBackStack(null)
       .commit(); 
}

从一个Activity的Fragment跳转到另外一个Activity的Fragment上

新建other_fragment.xml布局作为OtherActivity的一个Fragment。

 这种跳转与第三种跳转极为类似,我们只需要将上面的

Intent intent = new Intent(OtherActivity.this, MainActivity.class);

书写在对应的Fragment中,将OtherActivity.this更改为getActivity(),其他不用改变,就能完成跳转。

关键代码如下:

public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        Button ToButton = (Button) getActivity().findViewById(R.id.to_button);
        ToButton.setOnClickListener(new View.OnClickListener() {
            
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getActivity(), MainActivity.class);
                intent.putExtra("id",1);
                startActivity(intent);
            }
        });
    }

所有代码文件

最后附上所有的代码文件。  
MainActivity:

package com.example.fragment_activity_skiptest;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        getSupportFragmentManager()
                .beginTransaction()
                .replace(R.id.fragment_container,new MyFragment())
                .addToBackStack(null)
                .commit();
        int id = getIntent().getIntExtra("id", 0);
        if (id == 1) {
            getSupportFragmentManager()
                    .beginTransaction()
                    .replace(R.id.fragment_container,new YourFragment())
                    .addToBackStack(null)
                    .commit();
        }

    }
}

MyFragment:

package com.example.fragment_activity_skiptest;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;


public class MyFragment extends Fragment {

    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View contentView;
            contentView = inflater.inflate(R.layout.my_fragment, container, false);

        return contentView;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        Button myButton = (Button) getActivity().findViewById(R.id.my_button);

        Button myOther = (Button) getActivity().findViewById(R.id.my_other);
        myButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                /** 一、从同一个Activity的一个Fragment跳到另外一个Fragment*/
                //压栈式跳转
                getActivity().getSupportFragmentManager()
                        .beginTransaction()
                        .replace(R.id.fragment_container, new YourFragment(), null)
                        .addToBackStack(null)
                        .commit();

            }
        });
        myOther.setOnClickListener(new View.OnClickListener() {
            /**
             二、从一个Activity的Fragment跳转到另外一个Activity(等同于Activity之间的跳转(上下文是getActivity))
             */
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getActivity(),OtherActivity.class);
                startActivity(intent);
            }
        });
    }
}

OtherActivity:

package com.example.fragment_activity_skiptest;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

public class OtherActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_other);
        Button button = (Button)findViewById(R.id.to_MainActivity_YourFragment);
        Button button_back = (Button)findViewById(R.id.back);
        Button button_fm = (Button)findViewById(R.id.to_OtherFragment);
        button.setOnClickListener(new View.OnClickListener() {
            /*从一个Activity跳转到另外一个Activity的Fragment上
            例如我们要从OtherActivity跳转到MainActivity的YourFragment上去:
            首先,我们在OtherActivity中的跳转事件中给MainActivity传递一个名为id的参数:
            然后,我们在MainActivity里接收id值,对值进行判断,如果正确进行跳转操作:
            */
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(OtherActivity.this, MainActivity.class);
                intent.putExtra("id",1);
                startActivity(intent);

            }
        });
        button_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        button_fm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getSupportFragmentManager()
                        .beginTransaction()
                        .replace(R.id.frame_container, new OtherFragment(), null)
                        .addToBackStack(null)
                        .commit();
            }
        });
    }
}

OtherFragment:

package com.example.fragment_activity_skiptest;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;


public class OtherFragment extends Fragment {
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View contentView;
        contentView = inflater.inflate(R.layout.other_fragment, container, false);
        return contentView;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        Button ToButton = (Button) getActivity().findViewById(R.id.to_button);
        ToButton.setOnClickListener(new View.OnClickListener() {
            /*4、从一个Activity的Fragment跳转到另外一个Activity的Fragment上
            这种跳转与第三种跳转极为类似,我们只需要将
            Intent intent = new Intent(OtherActivity.this, MainActivity.class);
            书写在对应的Fragment中,将OtherActivity.this更改为getActivity(),其他不用改变,几个完成跳转.
            */
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getActivity(), MainActivity.class);
                intent.putExtra("id",1);
                startActivity(intent);
            }
        });
    }
}

YourFragment:

package com.example.fragment_activity_skiptest;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;


public class YourFragment extends Fragment {
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View contentView;
        contentView = inflater.inflate(R.layout.your_fragment, container, false);
        return contentView;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        Button myReturn = (Button) getActivity().findViewById(R.id.my_return);
        myReturn.setOnClickListener(new View.OnClickListener() {
            //返回到上一个Fragment(同一个Activity中)
            @Override
            public void onClick(View v) {
                getActivity().getSupportFragmentManager().popBackStack();
            }
        });
    }
}

activity_main.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">


    <FrameLayout
        android:id="@+id/fragment_container"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"/>


</LinearLayout>

activity_other.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:id="@+id/activity_other"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#d0ff05"
    >

    <FrameLayout
        android:id="@+id/frame_container"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1">
        <LinearLayout
            android:orientation="vertical"
            android:layout_width="match_parent"
            android:layout_height="match_parent">

            <TextView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="OtherActivity"
                android:textSize="50sp"
                android:gravity="center_horizontal"/>

            <Button
                android:id="@+id/to_MainActivity_YourFragment"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="To MainActivity YourFragment"
                android:textAllCaps="false"/>

            <Button
                android:id="@+id/to_OtherFragment"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="To OtherFragment"
                android:textAllCaps="false"/>

            <Button
                android:id="@+id/back"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="back"/>

        </LinearLayout>
    </FrameLayout>



</LinearLayout>

my_fragment.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="MyFragment"
        android:textSize="40sp"
        android:gravity="center_horizontal"/>

    <Button
        android:id="@+id/my_button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAllCaps="false"
        android:text="To YourFragment"/>

    <Button
        android:id="@+id/my_other"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAllCaps="false"
        android:text="To OtherActivity"/>

</LinearLayout>

other_fragment.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#ffffff">



    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="OtherFragment"
        android:textSize="40sp"
        android:gravity="center_horizontal"/>

    <Button
        android:id="@+id/to_button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAllCaps="false"
        android:text="To MainActivity YourFragment"/>

</LinearLayout>

your_fragment.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#0fa345">

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center_horizontal"
        android:textSize="40sp"
        android:text="YourFragment"/>

    <Button
        android:id="@+id/my_return"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="RETURN"
        />

</LinearLayout>

参考:Android Fragment的四种跳转

有关Fragment的四种跳转方式的更多相关文章

  1. ruby - 如何以所有可能的方式将字符串拆分为长度最多为 3 的连续子字符串? - 2

    我试图获取一个长度在1到10之间的字符串,并输出将字符串分解为大小为1、2或3的连续子字符串的所有可能方式。例如:输入:123456将整数分割成单个字符,然后继续查找组合。该代码将返回以下所有数组。[1,2,3,4,5,6][12,3,4,5,6][1,23,4,5,6][1,2,34,5,6][1,2,3,45,6][1,2,3,4,56][12,34,5,6][12,3,45,6][12,3,4,56][1,23,45,6][1,2,34,56][1,23,4,56][12,34,56][123,4,5,6][1,234,5,6][1,2,345,6][1,2,3,456][123

  2. ruby - 解析 RDFa、微数据等的最佳方式是什么,使用统一的模式/词汇(例如 schema.org)存储和显示信息 - 2

    我主要使用Ruby来执行此操作,但到目前为止我的攻击计划如下:使用gemsrdf、rdf-rdfa和rdf-microdata或mida来解析给定任何URI的数据。我认为最好映射到像schema.org这样的统一模式,例如使用这个yaml文件,它试图描述数据词汇表和opengraph到schema.org之间的转换:#SchemaXtoschema.orgconversion#data-vocabularyDV:name:namestreet-address:streetAddressregion:addressRegionlocality:addressLocalityphoto:i

  3. ruby-on-rails - 正确的 Rails 2.1 做事方式 - 2

    question的一些答案关于redirect_to让我想到了其他一些问题。基本上,我正在使用Rails2.1编写博客应用程序。我一直在尝试自己完成大部分工作(因为我对Rails有所了解),但在需要时会引用Internet上的教程和引用资料。我设法让一个简单的博客正常运行,然后我尝试添加评论。靠我自己,我设法让它进入了可以从script/console添加评论的阶段,但我无法让表单正常工作。我遵循的其中一个教程建议在帖子Controller中创建一个“评论”操作,以添加评论。我的问题是:这是“标准”方式吗?我的另一个问题的答案之一似乎暗示应该有一个CommentsController参

  4. 【鸿蒙应用开发系列】- 获取系统设备信息以及版本API兼容调用方式 - 2

    在应用开发中,有时候我们需要获取系统的设备信息,用于数据上报和行为分析。那在鸿蒙系统中,我们应该怎么去获取设备的系统信息呢,比如说获取手机的系统版本号、手机的制造商、手机型号等数据。1、获取方式这里分为两种情况,一种是设备信息的获取,一种是系统信息的获取。1.1、获取设备信息获取设备信息,鸿蒙的SDK包为我们提供了DeviceInfo类,通过该类的一些静态方法,可以获取设备信息,DeviceInfo类的包路径为:ohos.system.DeviceInfo.具体的方法如下:ModifierandTypeMethodDescriptionstatic StringgetAbiList​()Obt

  5. ruby - 鸭子输入字符串、符号和数组的优雅方式? - 2

    这是针对我无法破坏的现有公共(public)API,但我确实希望对其进行扩展。目前,该方法采用字符串或符号或任何其他在作为第一个参数传递给send时有意义的内容我想添加发送字符串、符号等列表的功能。我可以只使用is_a吗?数组,但还有其他发送列表的方法,这不是很像ruby​​。我将调用列表中的map,所以第一个倾向是使用respond_to?:map。但是字符串也会响应:map,所以这行不通。 最佳答案 如何将它们全部视为数组?String的行为与仅包含String的Array相同:deffoo(obj,arg)[*arg].eac

  6. ruby - 如何以编程方式删除实例上的 "singleton information"以使其编码(marshal)? - 2

    我创建了一个由于“在运行时执行的单例元类定义”而无法编码的对象(这段代码的描述是否正确?)。这是通过以下代码执行的:#defineclassXthatmyusesingletonclassmetaprogrammingfeatures#throughcallofmethod:break_marshalling!classXdefbreak_marshalling!meta_class=class我该怎么做才能使对象编码正确?是否可以从对象instance_of_x的classX中“移除”单例组件?我真的需要一个建议,因为我们的一些对象需要通过Marshal.dump序列化机制进行缓存。

  7. ruby - Paperclip:以编程方式分配图像并设置其名称 - 2

    使用Paperclip,我想从这样的URL抓取图像:require'open-uri'user.photo=open(url)问题是我最后得到一个像“open-uri20110915-4852-1o7k5uw”这样的文件名。有什么方法可以更改user.photo上的文件名?作为一个额外的变化,Paperclip将我的文件存储在S3上,所以如果我可以在初始分配中设置我想要的文件名就更好了,这样图像就会上传到正确的S3key。像这样:user.photo=open(url),:filename=>URI.parse(url).path 最佳答案

  8. ruby - 如何以编程方式检查证书是否已被吊销? - 2

    我正在开发一个xcode自动构建系统。在执行一些预构建验证时,我想检查指定的证书文件是否已被撤销。我了解securityverify-cert验证其他证书属性但不验证吊销。我如何检查撤销?我正在用Ruby编写构建系统,但我对任何语言的想法都持开放态度。我阅读了这个答案(Openssl-Howtocheckifacertificateisrevokedornot),但指向底部的链接(DoesOpenSSLautomaticallyhandleCRLs(CertificateRevocationLists)now?)进入的Material对我的目的来说有点过于复杂(用户上传已撤销的证书是一

  9. ruby-on-rails - 以 DRY 方式覆盖 ActiveRecord 中的 "find" - 2

    我有一些模型需要在它们上面放置自定义查找条件。例如,如果我有一个联系人模型,每次调用Contact.find时,我都想限制返回的联系人只属于正在使用的帐户。我通过Google找到了这个(我对其进行了一些自定义):defself.find(*args)with_scope(:find=>{:conditions=>"account_id=#{$account.id}"})dosuper(*args)endend这很好用,除了少数情况下account_id不明确,所以我将其调整为:defself.find(*args)with_scope(:find=>{:conditions=>"#{s

  10. ruby - 如何以编程方式将 mp3 转换为 itunes 可播放的 aac/m4a 文件? - 2

    我一直在寻找一种以编程方式或通过命令行将mp3转换为aac的方法,但没有成功。理想情况下,我有一段代码可以从我的Rails应用程序中调用,将mp3转换为aac。我安装了ffmpeg和libfaac,并能够使用以下命令创建aac文件:ffmpeg-itest.mp3-acodeclibfaac-ab163840dest.aac当我将输出文件的名称更改为dest.m4a时,它无法在iTunes中播放。谢谢! 最佳答案 FFmpeg提供AAC编码功能(如果您已编译它们)。如果您使用的是Windows,则可以从here获取完整的二进制文件。

随机推荐