如何保存和重用相同的片段实例? [英] How to save and reuse same instance of fragments?

查看:94
本文介绍了如何保存和重用相同的片段实例?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近开始使用片段创建了一个演示应用程序,如下所示:

I have recently started using fragments have created a demo app which looks like this:

单击每个按钮可在片段1,片段2和片段3之间切换。

Clicking on each button switches between fragment 1, Fragment 2, and Fragment 3.

我想要完成的是每个Fragment只有一个实例并重用它。 (请注意,所有片段都是动态创建和添加的)。目前我这样做是通过创建一个片段的HashMap并放置每个实例并从那里抓取它。

What I am trying to accomplish is to only have 1 instance of each Fragment and reuse that. (Please note that all the fragments are created and added dynamically). Currently I am doing this by creating a HashMap of fragment and placing each instance and grabbing it from there.

所以我的问题是:
有没有更好的方法这样做:
使用FragmentManager的putFragment(...)方法? putFragment(Bundle bundle,String key,Fragment fragment)我无法弄清楚如何在我的情况下使用它。如果有人能给我一个如何使用这种方法的例子。

So my questions are: Is there a better way of doing this: By using FragmentManager's putFragment(...) method? putFragment (Bundle bundle, String key, Fragment fragment) I can't figure out how to use it in my case. If anyone can give me an example of how to use this method.

在我的活动中保留每个片段的引用是否很昂贵?这会使所有碎片保持活着吗?我正在使用软参考来解决这个问题,但我不确定这是否是正确的方法。请指出我这样做的任何其他方式或让我知道这是否是实现这一目标的最佳方式。

Is it expensive to hold onto a reference of each fragment in my activity? Does this keep all the fragments alive? I am using soft reference to tackle this but I am not sure if this is the proper way of doing this. Please point me towards any alternative way of doing this or let me know if this is best way to accomplish this.

提前致谢。

这是我的代码:

UPDATE
我正在尝试重新使用后端堆栈中的片段,尝试仅在后端堆栈中不存在时添加它们。在我离开片段1后,下面的代码给出了非法状态异常 - >回到它 - >然后尝试按下后退按钮:

UPDATE: I am trying to reuse fragments from the back stack, trying to only add them if it does not exists in the back stack. The code below gives me the Illegal state exception after I navigate away from fragment one -> come back to it -> then try to press back button:

10-28 13:21:40.255: ERROR/MessageQueue-JNI(3548): java.lang.IllegalStateException: Fragment already added: FragmentOne{423db570 #0 id=0x7f050006 fragOne}

public class MainActivity extends Activity implements View.OnClickListener {

private Button btnOne;
private Button btnTwo;
private Button btnThree;

 /* Called when the activity is first created.
  */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    initialize();
    if(findViewById(R.id.fl) != null){
        if(savedInstanceState != null)
            return;
    }

    FragmentManager.enableDebugLogging(true);
    updateView("fragOne");
}

private void initialize(){
    btnOne = (Button) findViewById(R.id.button1);
    btnTwo = (Button) findViewById(R.id.button2);
    btnThree = (Button) findViewById(R.id.button3);
    btnOne.setOnClickListener(this);
    btnTwo.setOnClickListener(this);
    btnThree.setOnClickListener(this);
    fragHolder = new HashMap<String, SoftReference<Fragment>>();
}

private void updateView(String tag){
    FragmentTransaction ft = getFragmentManager().beginTransaction();
    Fragment frag = getFragmentManager().findFragmentByTag(tag);

    boolean addToStack = true;
    if(frag == null){
        if(tag.equals("fragOne"))
            frag = new FragmentOne();    
        else if(tag.equals("fragTwo"))
            frag = new FragmentTwo();
        else if(tag.equals("fragThree"))
            frag = new FragmentThree();
    }else{
        //Don't add to back stack
        addToStack = false;
    }
    ft.replace(R.id.fl, frag, tag);
    if(addToStack)
        ft.addToBackStack(null);
    ft.commit();
}

    @Override
    public void onClick(View v) {
        switch(v.getId()){
            case R.id.button1:
                updateView("fragOne");
                break;
            case R.id.button2:
                updateView("fragTwo");
                break;
            case R.id.button3:
                updateView("fragThree");
                break;
        }
    }
}


推荐答案

要演示 FragmentTransaction ,以下示例可能对您有所帮助。

To demonstrate a FragmentTransaction, the following sample might be helpful to you.

首先,您想要在您的活动的 onCreate()中完成所有初始化内容,但是我们会做一些更改。

First, you want to do all your initialization stuff in the onCreate() of your activity, which you have right, but we'll make a few changes.

public class MainActivity extends Activity implements View.OnClickListener {

private Button btnOne;
private Button btnTwo;
private Button btnThree;

/* Called when the activity is first created.*/
@Override
public void onCreate(Bundle savedInstanceState) 
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    initialize();
    if(findViewById(R.id.fl) != null)
    {
        if(savedInstanceState != null)
        {
            FragmentTransaction trans = getFragmentManager().beginTransaction();

            //This is where we add our first fragment
            trans.add(R.id.fl, new FragmentOne());
            trans.commit();
        }
    }
}

private void initialize()
{
    btnOne = (Button) findViewById(R.id.button1);
    btnTwo = (Button) findViewById(R.id.button2);
    btnThree = (Button) findViewById(R.id.button3);
    btnOne.setOnClickListener(this);
    btnTwo.setOnClickListener(this);
    btnThree.setOnClickListener(this);
}

public void onClick(View view)
{
    //Here is where we'll actually transfer the fragments

    FragmentTransaction trans = getFragmentManager().beginTransaction();
    switch(v.getId()){
        case R.id.button1:
            trans.replace(R.id.fl, new FragmentOne());
            trans.addToBackStack(null);
            trans.commit();
            break;
        case R.id.button2:
            trans.replace(R.id.fl, new FragmentTwo());
            trans.addToBackStack(null);
            trans.commit();
            break;
        case R.id.button3:
            trans.replace(R.id.fl, new FragmentThree());
            trans.addToBackStack(null);
            trans.commit();
            break;
    }
}

这将允许您轻松地从一个片段转换为下一个。

This will allow you to easily transition from one Fragment to the next.

这篇关于如何保存和重用相同的片段实例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆