替换 FrameLayout 布局中的片段 [英] Replace fragments in FrameLayout layout

查看:28
本文介绍了替换 FrameLayout 布局中的片段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经尝试了关于 android 片段的第一个谷歌页面上的所有教程,但我什么都做不了.

I have tried every tutorial on the first google page about android fragments, but I can't get anything to work.

所以我有一个导航栏活动,MainActivity.现在我想通过在抽屉中单​​击来更改片段.

So I have one navigation bar activity, MainActivity. Now I'd like to change fragments on a click in the drawer.

在我的 content_main(MainActivity 活动中的默认片段)中,我有一个框架布局,我希望将这些片段放入.我有以下片段:fragment_mainfragment_onefragment_two.我希望在单击导航抽屉中的按钮时显示这些.

In my content_main (default fragment in the MainActivity activity), I have a framelayout that I wish to put the fragments in. I have the following fragments: fragment_main, fragment_one and fragment_two. And I wish to show these when I click on a button in the nav drawer.

我想使用片段的原因是为了让导航抽屉保持在顶部.

The reason I want to use fragments is so that the nav drawer will stay on top.

提前致谢!

这是我将用来更改片段的函数:
只是为了测试,还没有完成.

Here is the function I'll use to change fragments:
It's just to test, not finished.

public void setFragment() {
    android.support.v4.app.FragmentTransaction transaction;
    transaction = getSupportFragmentManager().beginTransaction();
    transaction.replace(R.id.fragment_container, new LoginFragment());
    transaction.commit();
}

推荐答案

我解决了!

显然,我不得不使用 android.support.v4.app.Fragment; 而不是 android.app.Fragment;.这是我让它使用的代码:

Apparently, I had to use android.support.v4.app.Fragment; instead of android.app.Fragment;. This is the code I got it to work with:

protected void setFragment(Fragment fragment) {
    android.support.v4.app.FragmentTransaction t = getSupportFragmentManager().beginTransaction();
    t.replace(R.id.fragment_container, fragment);
    t.commit();
}

并设置它(从导航栏onNavigationItemSelected(),你这样做:

And to set it (from the nav bar onNavigationItemSelected(), you do this:

setFragment(new RoosterFragment());

我希望这能帮助其他人解决同样令人沮丧的问题.

I hope this helps others out with the same frustrating problem.

这篇关于替换 FrameLayout 布局中的片段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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