本文选自StackOverflow(简称:SOF)精选问答汇总系列文章之一,本系列文章将为读者分享国外最优质的精彩问与答,供读者学习和了解国外最新技术,本文为大家讲解如何进行fragment中的来回切换


问:Ijaz Ahmed

我想要对fragment中的fragment进行操作,在按后退按钮的时候出现了问题。应用程序主屏幕上有很多按钮,按下每个按钮都会出现新的fragment(它也被包含在另一个fragment内)。按下按钮1(已替换fragment),可以进行动态的添加或者是替换片段。如果按下按钮后,再去按它,就会得到:

1
2
"Duplicate id 0x7f05000a, tag null, or parent id 0x7f050009 with
another fragment for com........ fragmentname"

这意味着已经添加过fragment,有谁可以帮我完成fragment的相关设定,并顺利的完成来回切换?

如下是,MainActiviy的代码,它可以控制动态添加/替换fragment:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
public class FragmentInsideFragmentTestActivity extends Activity {
 
 private Button button1;
 private Button button2;
 private Button button3;
 private Button button4;
 
 
 /** Called when the activity is first created. */
@Override
 public void onCreate(Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);
 setContentView(R.layout.main);
 
 button1 =(Button) this.findViewById(R.id.button1);
 button1.setOnClickListener(new View.OnClickListener() {
     public void onClick(View view) {
         onButtonClick(view);
 
         }
 });
 
 button2 =(Button) this.findViewById(R.id.button2);
 button2.setOnClickListener(new View.OnClickListener() {
     public void onClick(View view) {
         onButtonClick(view);
 
         }
 });
 
 button3 =(Button) this.findViewById(R.id.button3);
 button3.setOnClickListener(new View.OnClickListener() {
     public void onClick(View view) {
         onButtonClick(view);
 
         }
 });
 
 button4 =(Button) this.findViewById(R.id.button4);
 button4.setOnClickListener(new View.OnClickListener() {
     public void onClick(View view) {
         onButtonClick(view);
 
         }
 });
 
  }
 
 public void onButtonClick(View v) {
         Fragment fg;
         switch (v.getId()) {
         case R.id.button1:
                 fg=FirstFragment.newInstance();
                 replaceFragment(fg);
                 break;
         case R.id.button2:
                 fg=SecondFragment.newInstance();
                 replaceFragment(fg);
                 break;
         case R.id.button3:
                 fg=FirstFragment.newInstance();
                 replaceFragment(fg);
                 break;
         case R.id.button4:
                 fg=SecondFragment.newInstance();
                 replaceFragment(fg);
                 break;
         }
 }
 
 private void replaceFragment(Fragment newFragment) {
 
 FragmentTransaction trasection =
 getFragmentManager().beginTransaction();
 if(!newFragment.isAdded()){
         try{
                 //FragmentTransaction trasection =
         getFragmentManager().beginTransaction();
         trasection.replace(R.id.linearLayout2, newFragment);
         trasection.addToBackStack(null);
         trasection.commit();
 
         }catch (Exception e) {
                         // TODO: handle exception
                  //AppConstants.printLog(e.getMessage());
 
                 }
 }else
         trasection.show(newFragment);
 
    }
  }

如下是Layout : main.xml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
 
  <LinearLayout android:id="@+id/linearLayout1"
          android:layout_width="match_parent"
          android:layout_height="wrap_content"
          android:orientation="horizontal">
          <Button android:layout_width="wrap_content"
                  android:id="@+id/button1"
                  android:layout_height="wrap_content"
                  android:text="Button1"></Button>
          <Button android:text="Button2"
                  android:id="@+id/button2"
                  android:layout_width="wrap_content"
                  android:layout_height="wrap_content"></Button>
          <Button android:text="Button3"
                  android:id="@+id/button3"
                  android:layout_width="wrap_content"
                  android:layout_height="wrap_content"></Button>
          <Button android:text="Button4"
                  android:id="@+id/button4"
                  android:layout_width="wrap_content"
                  android:layout_height="wrap_content"></Button>
  </LinearLayout>
 
 <LinearLayout android:id="@+id/linearLayout2"
  android:layout_width="match_parent"
   android:layout_height="wrap_content"
  android:orientation="horizontal"></LinearLayout>
    </LinearLayout>

以上就是我遇到的问题,希望大家可以为我解答。

答:CommonsWare

(最佳答案)

你可以用getChildFragmentManager()进行fragment嵌套操作,但这也意味着你的Android支持包版本的API级别要在11-16之间。主要是因为,即使在配置上存在fragment的自带版本,但是也未必可以支getChildFragmentManager()。

答:Napolean

fragment可以嵌套在其它的fragment中,但每次调用onDestroyView()时,你都需要从parent Fragment中删掉它,然后将它添加到OnCreateView()中的parent Fragment。具体方法如下:

1
2
3
4
5
6
7
8
9
10
@Override
    public void onDestroyView()
    {
                FragmentManager mFragmentMgr= getFragmentManager();
        FragmentTransaction mTransaction = mFragmentMgr.beginTransaction();
                Fragment childFragment =mFragmentMgr.findFragmentByTag("qa_fragment")
        mTransaction.remove(childFragment);
        mTransaction.commit();
        super.onDestroyView();
    }

答:Vetal.lebed

我的解决办法是,使用支持库(Support library)和ViewPager。你可以禁用一些不必要的程序,具体方法如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
public class TestFragment extends Fragment{
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View v = inflater.inflate(R.layout.frag, container, false);
    final ArrayList<Fragment> list = new ArrayList<Fragment>();
 
    list.add(new TrFrag());
    list.add(new TrFrag());
    list.add(new TrFrag());
 
    ViewPager pager = (ViewPager) v.findViewById(R.id.pager);
    pager.setAdapter(new FragmentPagerAdapter(getActivity().getSupportFragmentManager()) {
        @Override
        public Fragment getItem(int i) {
            return list.get(i);
        }
 
        @Override
        public int getCount() {
            return list.size();
        }
    });
    return v;
}

原文链接:http://stackoverflow.com/questions/6672066/fragment-inside-fragment?rq=1

http://android.9tech.cn/news/2013/1202/39041.html

如何进行fragment中的来回切换?的更多相关文章

  1. 【转】Android Fragment中使用SurfaceView切换时闪一下黑屏的解决办法

    重构了下之前自己的一个新闻客户端,全部使用了Fragment来进行页面切换,只有一个入口Activity作为程序的启动Activity,其中有一个界面需要调用摄像头识别二维码, 于是就会用到Surfa ...

  2. Fragment碎片频繁来回切换的时候报java.lang.IllegalStateException: No activity

    出现这个问题的原因是因为使用的transcation.replace(fragmentTwo);的方式进行碎片切换的. 解决方案是使用add和show.hide方法组合实现碎片的切换(应该是显示.隐藏 ...

  3. [Android Pro] Fragment中使用SurfaceView切换时闪一下黑屏的解决办法

    方法一.在Activity的onCreate中添加如下代码 getWindow().setFormat(PixelFormat.TRANSLUCENT); reference to :  http:/ ...

  4. 关于含RecyclerView的fragment来回切换时页面自动滑动到底部的解决方法

    原因: 在fragment中来回切换时RecyclerView获得了焦点,而RecyclerView的 focusableOnTouchMode属性默认是true,所以在切换时RecyclerView ...

  5. fragment中嵌套viewpager,vierpager中有多个fragment,不显示 .

    fragment中嵌套viewpager,vierpager中有多个fragment,不显示 ... 现在好多应用流行一种布局.底部几个工具栏选项,上面也有类似tab的选项. 底部用RadioGrou ...

  6. Android Fragment使用(四) Toolbar使用及Fragment中的Toolbar处理

    Toolbar作为ActionBar使用介绍 本文介绍了在Android中将Toolbar作为ActionBar使用的方法. 并且介绍了在Fragment和嵌套Fragment中使用Toolbar作为 ...

  7. Fragment中监听onKey事件,没你想象的那么难。

    项目中越来越多的用到Fragment,在用Fragment取代TabHost的时候遇到了一个问题,我们都知道,TabHost的Tab为Activity实例,有OnKey事件,但是Fragment中没有 ...

  8. [Android Pro] fragment中嵌套viewpager,vierpager中有多个fragment,不显示

    referece to :  http://blog.csdn.net/mybook1122/article/details/24003343 现在好多应用流行一种布局.底部几个工具栏选项,上面也有类 ...

  9. (17/24) webpack实战技巧:生产环境和开发环境并行设置,实现来回切换

    1. 概述 生产环境和开发环境所需依赖是不同: --开发依赖:就是开发中用到而发布时用不到的.在package.json里面对应的就是devDependencies下面相关配置. --生产依赖: 就是 ...

随机推荐

  1. C#经典系列-键值对

    1.ToDictionary,ToLookup 从图中我们看到有四个ToXXX的方法,其中ToArray和ToList,用的是非常非常多 我们有这样的一个实体 class student { publ ...

  2. Java多线程编程(一)

    1.Java创建多线程的方法一:(1)实现Runnable接口并实现其中的run()方法:(2)将Runable对象提交给一个Thread构造器,调用start()方法. [程序实例]单线程 publ ...

  3. 从VSS到SVN再到Git 记Git的基本操作

    Source code control 一直是软件开发过程中重要的环节,从最初的纯文件备份,到使用工具进行管理.Source code control 工具的作用也不仅仅只是单纯的对同一个版本进行管理 ...

  4. 一般处理程序中使用Session出现未将对象引用设置到对象的实例

    遇到问题:未将对象引用设置到对象的实例 那就在你的一般处理程序中加入红色背景的代码吧 using System; using System.Collections.Generic; using Sys ...

  5. ubuntu navicat110 for mysql 装配与破解

    安装:解压后即可用.目录下的start_navicat文件为可执行文件. 破解:(找过好几个注册码都不能用,注册码生成器都是windows平台的) ----第一次执行start_navicat时,会在 ...

  6. codevs 3693 数三角形

    /* n*m个点中选3个 再排除三点共线 共线分两类 1 在横线或者竖线上 m*C(n,3) n*C(m,3) 2 在对角线上 这个比较麻烦 以为对角线和矩阵是一一对应的 我们转化成求矩阵 并且保证有 ...

  7. (转)使用DataTime这个类来获取当前的时间

    我们可以通过使用DataTime这个类来获取当前的时间.通过调用类中的各种方法我们可以获取不同的时间:如:日期(--).时间(::).日期+时间(-- ::)等. //获取日期+时间 DateTime ...

  8. linux free命令建检查内存状态

    前端时间发现博客服务器物理内存使用过高问题,就是使用linux free命令检查的,这次详细介绍下这个命令. 命 令: free 功能说明:显示内存状态.语 法: free [-bkmotV][-s  ...

  9. 怎样取得数组对象和arralist 的长度

    数组用length属性 ArrayList用size()方法

  10. 用CAGradientLayer实现渐变色动画

    效果图: github:https://github.com/RinpeChen/CAGradientLayerBasicDemo