Replace fragments in the FrameLayout layout

综合技术 2017-11-15

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

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

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.

Thanks in advance!

Edit: 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();
}

I solved it!

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();
}

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.

Hello, buddy!

责编内容by:Hello, buddy! (源链)。感谢您的支持!

您可能感兴趣的

Hide linear layout on runtime in Android I am having following layout What I want to do is to show/hide ...
进程系列第二篇—Zygote进程的创建流程... 目录.png 概述: 本文(基于Android O源码)主要讲解Zygote进程创建流程,线程容易创建,但进程的相关的东西都被系统...
Nearby Connections API 2.0 House advertise the availability and rates of their driveways, So your phone co...
Glide4.6.1 GlideApp 无法生成的问题 依赖配置如下 Glide 4.6.1的sdk build版本必须为>=27,必须保证所有的support 的版本为相同并且为27.1.0 ...
一步步探索学习Android Touch事件分发传递机制(二)... 前言 1. 探究的内容 在上一篇文章 《一步步探索学习Android Touch事件分发传递机制(一)》 中,已经 以ACTION...