替换Fragment&在android中添加Fragment

时间:2015-03-25 10:50:58

标签: android fragment

我使用此代码在 android 4.0.4

上将片段替换为另一个
FragmentManager manager;
manager=getFragmentManager();
FragmentTransaction transaction=manager.beginTransaction();
 Fragment1 f1=new Fragment1();
 Fragment2 f2=new Fragment2();
public void replace_one(View v)
    {
        Fragment1 f1=(Fragment1)manager.findFragmentByTag("f1");
        transaction.remove(f1);             
        transaction.replace(R.id.place,f2,"f2");
        transaction.commit();
}

此代码有效,但对于 android 4.4.2不起作用 ,对于Android 4.1.2,它正在运行

如果我使用此代码:

   FragmentManager manager;
    manager=getFragmentManager();
    FragmentTransaction transaction=manager.beginTransaction();
     Fragment1 f1=new Fragment1();
     Fragment2 f2=new Fragment2();
    public void replace_one(View v)
        {
            Fragment1 f1=(Fragment1)manager.findFragmentByTag("f1");
            transaction.remove(f1);             
            transaction.add(R.id.place,f2,"f2");
            transaction.commit();
    }

此代码适用于Android 4.4.2 ,但对于Android 4.0.4不起作用 ,对于Android 4.1.2,它是工作

有什么问题?

1 个答案:

答案 0 :(得分:0)

以下是添加或替换片段的方法:

   //TO add your fragment
    SomeFragment fragment = SomeFragment.getInstance()//If you have made your fragment singleton.
    getFragmentManager().beginTransaction().add(YOUR_CONTAINER_ID, YOUR FRAGMENT, YOUR_FRAGMENT_UNIQUE_TAG).addToBackStack(null).commit();

    //TO replace your fragment
    SomeFragment fragment = SomeFragment.getInstance()//If you have made your fragment singleton.
    getFragmentManager().beginTransaction().replace(YOUR_CONTAINER_ID, YOUR FRAGMENT, YOUR_FRAGMENT_UNIQUE_TAG).addToBackStack(null).commit();

导入:

import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;