如何在代码中使用FragmentTransaction?

时间:2014-03-29 21:45:22

标签: android replace fragment

我想用以下代码更改容器中的片段:

public static class PlaceholderFragment extends Fragment {

    public PlaceholderFragment() {
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_app_launch, container, false);

        SharedPreferences getSharedPreferences = getActivity().getSharedPreferences("meetme_first_start", Context.MODE_PRIVATE);
        int firstStart = getSharedPreferences.getInt("first_start", 0);
        if (firstStart == 0) {
            FragmentTransaction ft = new FragmentTransaction();
            ft.replace(R.id.container, new TargetFragment());

        }

        return rootView;
    }
}

但它说cannot instantiate the type FragmentTransaction。有人知道帮忙吗?

2 个答案:

答案 0 :(得分:2)

以这种方式获取FragmentTransaction实例的正确方法是:

FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();

或者单行:

FragmentTransaction ft = getFragmentManager().beginTransaction();

答案 1 :(得分:2)

使用此,

         getFragmentManager().beginTransaction().replace(android.R.id.container, new TargetFragment()).commit();