如何在android中添加片段活动?

时间:2016-05-23 09:44:17

标签: android

我想将活动替换为片段,此代码无效。

Intent intent = new Intent(Activity.this, Fragment.class);
startActivity(intent);
finish();

3 个答案:

答案 0 :(得分:1)

您无法从活动切换到片段,因为片段没有活动就没有自己的存在。即片段在活动内部起作用 基本上,Fragments主要用于创建多窗格屏幕。

如果你可以替换上面代码示例中提到的片段(与Activity关联)来更改UI,那么在Activity内部。

答案 1 :(得分:0)

在您的活动中尝试这样做

@Override
public void replaceFragment(Fragment fragment, boolean addToBackStack) {

    FragmentTransaction transaction = getSupportFragmentManager()
            .beginTransaction();

    if (addToBackStack) {
        transaction.addToBackStack(null);

    } else {
        getSupportFragmentManager().popBackStack(null,
                FragmentManager.POP_BACK_STACK_INCLUSIVE);

    }
    transaction.replace(R.id.flContent, fragment);
    transaction.commitAllowingStateLoss();
    getSupportFragmentManager().executePendingTransactions();

}

并像这样使用

    YourFragment mYourFrag = new YourFragment ();
    replaceFragment(mYourFrag , false);

答案 2 :(得分:0)

创建一个类似

的Fragmen类
public class FragmentName extends android.support.v4.app.Fragment {}

然后你可以投射一个活动来查看:

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View returner = null;
    Intent intent = new Intent([CONTEXT],[CLASSNAME.class]);
    Bundle args = this.getArguments();
        final Window w = [LocalActivityManager].startActivity("Title", intent);
        final View wd = w != null ? w.getDecorView() : null;

        if (wd != null) {
            ViewParent parent = wd.getParent();
            if(parent != null) {
                ViewGroup v = (ViewGroup)parent;
                v.removeView(wd);
            }

            wd.setVisibility(View.VISIBLE);
            wd.setFocusableInTouchMode(true);
            if(wd instanceof ViewGroup) {
                ((ViewGroup) wd).setDescendantFocusability(ViewGroup.FOCUS_AFTER_DESCENDANTS);
            }
        }
    returner = wd;
    return returner;
}
相关问题