我在android studio中有基于片段的活动

                    someFragment fragment = new someFragment();
                    android.support.v4.app.FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
                    fragmentttTransaction.replace(R.id.frame,fragment);
                    fragmentttTransaction.commit();


我想通过一个函数来调用它,就像这样:

        public void gotofragment(String classname) {

    ...
}


我试图使用Class.forName(classname).newInstance(),但是它没有用,android studio显示错误。

感谢您的帮助,在此先感谢您

最佳答案

您可以执行以下操作:

    private void showFragment(String fragmentId) {
    FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
    Fragment fragment = getSupportFragmentManager().findFragmentByTag(fragmentId);
    if (fragment == null) {
        if (fragmentId.equals("Type1") {
            fragment = Type1Fragment.newInstance();
        }else if (fragmentId.equals("Type2") {
            fragment = Type2Fragment.newInstance();
        }
        ft.replace(R.id.container, fragment, fragmentId).commit();
    }
}

07-26 08:49