Fragment的四种跳转方式

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

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

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

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

 1 <?xml version="1.0" encoding="utf-8"?>
 2 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
 3     android:orientation="vertical"
 4     android:layout_width="match_parent"
 5     android:layout_height="match_parent">
 6  
 7  
 8     <FrameLayout
 9         android:id="@+id/fragment_container"
10         android:layout_width="match_parent"
11         android:layout_height="0dp"
12         android:layout_weight="1"/>
13  
14  
15 </LinearLayout>

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

 1 <?xml version="1.0" encoding="utf-8"?>
 2 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
 3     android:orientation="vertical"
 4     android:layout_width="match_parent"
 5     android:layout_height="match_parent">
 6  
 7     <TextView
 8         android:layout_width="match_parent"
 9         android:layout_height="wrap_content"
10         android:text="MyFragment"
11         android:textSize="40sp"
12         android:gravity="center_horizontal"/>
13  
14     <Button
15         android:id="@+id/my_button"
16         android:layout_width="wrap_content"
17         android:layout_height="wrap_content"
18         android:textAllCaps="false"
19         android:text="To YourFragment"/>
20  
21     <Button
22         android:id="@+id/my_other"
23         android:layout_width="wrap_content"
24         android:layout_height="wrap_content"
25         android:textAllCaps="false"
26         android:text="To OtherActivity"/>
27  
28 </LinearLayout>

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

 1 public class MainActivity extends AppCompatActivity {
 2  
 3     @Override
 4     protected void onCreate(Bundle savedInstanceState) {
 5         super.onCreate(savedInstanceState);
 6         setContentView(R.layout.activity_main);
 7         getSupportFragmentManager()
 8                 .beginTransaction()
 9                 .replace(R.id.fragment_container,new MyFragment())
10                 .addToBackStack(null)
11                 .commit();
12  
13     }
14 }

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

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

 1 public class YourFragment extends Fragment {
 2     public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
 3         View contentView;
 4         contentView = inflater.inflate(R.layout.your_fragment, container, false);
 5         return contentView;
 6     }
 7  
 8     @Override
 9     public void onActivityCreated(@Nullable Bundle savedInstanceState) {
10         super.onActivityCreated(savedInstanceState);
11         Button myReturn = (Button) getActivity().findViewById(R.id.my_return);
12         myReturn.setOnClickListener(new View.OnClickListener() {
13             //返回到上一个Fragment(同一个Activity中)
14             @Override
15             public void onClick(View v) {
16                 getActivity().getSupportFragmentManager().popBackStack();
17             }
18         });
19     }
20 }

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

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

 1 myButton.setOnClickListener(new View.OnClickListener() {
 2             @Override
 3             public void onClick(View v) {
 4                 /* 一、从同一个Activity的一个Fragment跳到另外一个Fragment*/
 5                 //压栈式跳转
 6                 getActivity().getSupportFragmentManager()
 7                         .beginTransaction()
 8                         .replace(R.id.fragment_container, new YourFragment(), null)
 9                         .addToBackStack(null)
10                         .commit();
11  
12             }
13         });

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

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

跳转关键代码:

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

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

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

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

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

1 int id = getIntent().getIntExtra("id", 0);
2 if (id == 1) {      
3      getSupportFragmentManager()
4        .beginTransaction()
5        .replace(R.id.fragment_container,new YourFragment())
6        .addToBackStack(null)
7        .commit(); 
8 }

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

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

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

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

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

关键代码如下:

 1 public void onActivityCreated(@Nullable Bundle savedInstanceState) {
 2         super.onActivityCreated(savedInstanceState);
 3         Button ToButton = (Button) getActivity().findViewById(R.id.to_button);
 4         ToButton.setOnClickListener(new View.OnClickListener() {
 5             
 6             @Override
 7             public void onClick(View v) {
 8                 Intent intent = new Intent(getActivity(), MainActivity.class);
 9                 intent.putExtra("id",1);
10                 startActivity(intent);
11             }
12         });
13     }

所有代码文件

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

 1 package com.example.fragment_activity_skiptest;
 2  
 3 import android.content.Intent;
 4 import android.support.v7.app.AppCompatActivity;
 5 import android.os.Bundle;
 6 import android.view.View;
 7  
 8 public class MainActivity extends AppCompatActivity {
 9  
10     @Override
11     protected void onCreate(Bundle savedInstanceState) {
12         super.onCreate(savedInstanceState);
13         setContentView(R.layout.activity_main);
14         getSupportFragmentManager()
15                 .beginTransaction()
16                 .replace(R.id.fragment_container,new MyFragment())
17                 .addToBackStack(null)
18                 .commit();
19         int id = getIntent().getIntExtra("id", 0);
20         if (id == 1) {
21             getSupportFragmentManager()
22                     .beginTransaction()
23                     .replace(R.id.fragment_container,new YourFragment())
24                     .addToBackStack(null)
25                     .commit();
26         }
27  
28     }
29 }

MyFragment:

 1 package com.example.fragment_activity_skiptest;
 2  
 3 import android.content.Intent;
 4 import android.os.Bundle;
 5 import android.support.annotation.Nullable;
 6 import android.support.v4.app.Fragment;
 7 import android.view.LayoutInflater;
 8 import android.view.View;
 9 import android.view.ViewGroup;
10 import android.widget.Button;
11  
12  
13 public class MyFragment extends Fragment {
14  
15     public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
16         View contentView;
17             contentView = inflater.inflate(R.layout.my_fragment, container, false);
18  
19         return contentView;
20     }
21  
22     @Override
23     public void onActivityCreated(@Nullable Bundle savedInstanceState) {
24         super.onActivityCreated(savedInstanceState);
25         Button myButton = (Button) getActivity().findViewById(R.id.my_button);
26  
27         Button myOther = (Button) getActivity().findViewById(R.id.my_other);
28         myButton.setOnClickListener(new View.OnClickListener() {
29             @Override
30             public void onClick(View v) {
31                 /** 一、从同一个Activity的一个Fragment跳到另外一个Fragment*/
32                 //压栈式跳转
33                 getActivity().getSupportFragmentManager()
34                         .beginTransaction()
35                         .replace(R.id.fragment_container, new YourFragment(), null)
36                         .addToBackStack(null)
37                         .commit();
38  
39             }
40         });
41         myOther.setOnClickListener(new View.OnClickListener() {
42             /**
43              二、从一个Activity的Fragment跳转到另外一个Activity(等同于Activity之间的跳转(上下文是getActivity))
44              */
45             @Override
46             public void onClick(View v) {
47                 Intent intent = new Intent(getActivity(),OtherActivity.class);
48                 startActivity(intent);
49             }
50         });
51     }
52 }

OtherActivity:

 1 package com.example.fragment_activity_skiptest;
 2  
 3 import android.content.Intent;
 4 import android.support.v7.app.AppCompatActivity;
 5 import android.os.Bundle;
 6 import android.view.View;
 7 import android.widget.Button;
 8  
 9 public class OtherActivity extends AppCompatActivity {
10  
11     @Override
12     protected void onCreate(Bundle savedInstanceState) {
13         super.onCreate(savedInstanceState);
14         setContentView(R.layout.activity_other);
15         Button button = (Button)findViewById(R.id.to_MainActivity_YourFragment);
16         Button button_back = (Button)findViewById(R.id.back);
17         Button button_fm = (Button)findViewById(R.id.to_OtherFragment);
18         button.setOnClickListener(new View.OnClickListener() {
19             /*从一个Activity跳转到另外一个Activity的Fragment上
20             例如我们要从OtherActivity跳转到MainActivity的YourFragment上去:
21             首先,我们在OtherActivity中的跳转事件中给MainActivity传递一个名为id的参数:
22             然后,我们在MainActivity里接收id值,对值进行判断,如果正确进行跳转操作:
23             */
24             @Override
25             public void onClick(View v) {
26                 Intent intent = new Intent(OtherActivity.this, MainActivity.class);
27                 intent.putExtra("id",1);
28                 startActivity(intent);
29  
30             }
31         });
32         button_back.setOnClickListener(new View.OnClickListener() {
33             @Override
34             public void onClick(View v) {
35                 finish();
36             }
37         });
38         button_fm.setOnClickListener(new View.OnClickListener() {
39             @Override
40             public void onClick(View v) {
41                 getSupportFragmentManager()
42                         .beginTransaction()
43                         .replace(R.id.frame_container, new OtherFragment(), null)
44                         .addToBackStack(null)
45                         .commit();
46             }
47         });
48     }
49 }

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:

 1 <?xml version="1.0" encoding="utf-8"?>
 2 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
 3     android:orientation="vertical"
 4     android:id="@+id/activity_other"
 5     android:layout_width="match_parent"
 6     android:layout_height="match_parent"
 7     android:background="#d0ff05"
 8     >
 9  
10     <FrameLayout
11         android:id="@+id/frame_container"
12         android:layout_width="match_parent"
13         android:layout_height="0dp"
14         android:layout_weight="1">
15         <LinearLayout
16             android:orientation="vertical"
17             android:layout_width="match_parent"
18             android:layout_height="match_parent">
19  
20             <TextView
21                 android:layout_width="match_parent"
22                 android:layout_height="wrap_content"
23                 android:text="OtherActivity"
24                 android:textSize="50sp"
25                 android:gravity="center_horizontal"/>
26  
27             <Button
28                 android:id="@+id/to_MainActivity_YourFragment"
29                 android:layout_width="wrap_content"
30                 android:layout_height="wrap_content"
31                 android:text="To MainActivity YourFragment"
32                 android:textAllCaps="false"/>
33  
34             <Button
35                 android:id="@+id/to_OtherFragment"
36                 android:layout_width="wrap_content"
37                 android:layout_height="wrap_content"
38                 android:text="To OtherFragment"
39                 android:textAllCaps="false"/>
40  
41             <Button
42                 android:id="@+id/back"
43                 android:layout_width="wrap_content"
44                 android:layout_height="wrap_content"
45                 android:text="back"/>
46  
47         </LinearLayout>
48     </FrameLayout>
49  
50  
51  
52 </LinearLayout>

my_fragment.xml:

 1 <?xml version="1.0" encoding="utf-8"?>
 2 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
 3     android:orientation="vertical"
 4     android:layout_width="match_parent"
 5     android:layout_height="match_parent">
 6  
 7     <TextView
 8         android:layout_width="match_parent"
 9         android:layout_height="wrap_content"
10         android:text="MyFragment"
11         android:textSize="40sp"
12         android:gravity="center_horizontal"/>
13  
14     <Button
15         android:id="@+id/my_button"
16         android:layout_width="wrap_content"
17         android:layout_height="wrap_content"
18         android:textAllCaps="false"
19         android:text="To YourFragment"/>
20  
21     <Button
22         android:id="@+id/my_other"
23         android:layout_width="wrap_content"
24         android:layout_height="wrap_content"
25         android:textAllCaps="false"
26         android:text="To OtherActivity"/>
27  
28 </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:

 1 <?xml version="1.0" encoding="utf-8"?>
 2 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
 3     android:orientation="vertical"
 4     android:layout_width="match_parent"
 5     android:layout_height="match_parent"
 6     android:background="#0fa345">
 7  
 8     <TextView
 9         android:layout_width="match_parent"
10         android:layout_height="wrap_content"
11         android:gravity="center_horizontal"
12         android:textSize="40sp"
13         android:text="YourFragment"/>
14  
15     <Button
16         android:id="@+id/my_return"
17         android:layout_width="wrap_content"
18         android:layout_height="wrap_content"
19         android:text="RETURN"
20         />
21  
22 </LinearLayout>

参考:Android Fragment的四种跳转

我的CSDN:Fragment的四种跳转方式_SY_XLR的博客-CSDN博客_fragment跳转

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: 在Android中,可以使用FragmentManager来管理Fragment跳转。具体步骤如下: 1. 获取FragmentManager对象: FragmentManager fragmentManager = getSupportFragmentManager(); 2. 开始Fragment事务: FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction(); 3. 创建要跳转Fragment对象: MyFragment myFragment = new MyFragment(); 4. 调用FragmentTransaction的replace方法,将当前Fragment替换为要跳转FragmentfragmentTransaction.replace(R.id.container, myFragment); 5. 调用FragmentTransaction的commit方法,提交事务: fragmentTransaction.commit(); 其中,R.id.container是一个FrameLayout,用于显示Fragment的布局容器。 ### 回答2: 在Android中,使用Fragment的一个常见的需求是在一个Fragment中点击某个按钮或者view后跳转到另一个Fragment,也就是所谓的Fragment跳转Fragment。 在实现这个需求之前,需要先明确一些基本概念。在Android中,使用Fragment的最基本的方式是使用FragmentTransaction来进行添加、移除、替换、隐藏等操作。当一个新的Fragment需要被展示时,也就是所谓的Fragment跳转Fragment时,我们需要使用FragmentTransaction来进行以下步骤: 1. 创建要跳转Fragment实例。 2. 使用FragmentManager获取FragmentTransaction实例。 3. 调用FragmentTransaction的替换方法(replace)来将当前Fragment替换为要跳转Fragment。 4. 添加到回退栈(addToBackStack)中。 5. 调用FragmentTransaction的提交方法(commit)来提交这一操作。 示例代码如下: ``` FragmentTransaction transaction = getSupportFragmentManager().beginTransaction(); transaction.replace(R.id.fragment_container, new MyFragment()); transaction.addToBackStack(null); transaction.commit(); ``` 在这段代码中,我们使用了SupportFragmentManager来获取了一个FragmentTransaction对象,并将其替换为了新的Fragment,并将其添加到回退栈中。最后,调用了提交方法来提交这一操作。 需要注意的是,在跳转Fragment时,我们也可以传递一些数据给新的Fragment,例如某些参数、对象等。我们可以使用Bundle将这些数据打包传递给新的Fragment。在新的Fragment中,我们可以使用getArguments()方法获取这些数据。 总体来说,Fragment跳转Fragment是Android中常见的一种场景,使用FragmentTransaction进行操作可以轻松地实现这一需求。在进行操作时,需要注意保存当前状态并添加到回退栈中,以便用户可以使用返回按钮返回上一个Fragment。 ### 回答3: Fragment 跳转 Fragment 是指在一个 Fragment 中通过代码的方式启动另一个 Fragment。在实际开发中,这种方式常常被用于实现页面之间的跳转或者数据的传递等操作。 在 Android 中,Fragment 跳转 Fragment 有多种方式,其中最常用的方式是使用 FragmentManager 开启一个新的 Fragment,具体流程如下: 1. 首先需要获取到 FragmentManager 对象,可以通过 getActivity().getSupportFragmentManager() 方法获取当前 Fragment 所在的 Activity 的 FragmentManager 对象。 2. 创建一个新的 Fragment 对象,这个对象可以在 FragmentManager 中进行管理,在后面我们会用到。 3. 随着 Fragment 的增多,一个问题也就显现出来,如何在父 Fragment 中实现多个 Fragment 之间的切换?这个时候可以选择使用 FragmentTransaction 对象,通过 add()、replace() 等方法实现对 Fragment 的增删操作。 代码实现如下: // 获取 FragmentManager 对象 FragmentManager fragmentManager = getActivity().getSupportFragmentManager(); // 创建一个新的 Fragment 对象 SecondFragment fragment = new SecondFragment(); // 开启一个事务 FragmentTransaction transaction = fragmentManager.beginTransaction(); // 通过 add()、replace() 等方法实现对 Fragment 的增删操作 transaction.replace(R.id.container, fragment); transaction.addToBackStack(null); // 提交事务,启动 Fragment transaction.commit(); 在这段代码中,R.id.container 表示存放 Fragment 的容器,这个可以根据实际需要进行修改。 同时,我们还需要注意 addToBackStack() 方法的使用。这个方法可以将当前 Fragment 加入 BackStack 中,也就是将当前 Fragment 放入到一个栈中,方便用户在返回时直接返回到上一个 Fragment。需要注意的是,如果不使用 addToBackStack() 方法,则用户在返回时会直接退出当前 Activity。 总之,Fragment 跳转 Fragment 功能十分重要,能够帮助开发者实现程序中各种场景的操作。通过 Fragment 嵌套来实现页面嵌套,通过 Fragment 之间的跳转来实现页面之间的切换,是 Android 开发中不可或缺的一部分。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值