FragmentTransaction not doing anything

末鹿安然 提交于 2019-12-04 02:41:35

Well I got it working. Both answers given to this questions correctly tells one reason for my code to not work as expected. But there were 2 errors in my code.

using fragmentTransaction.add() won't show new fragment over old one. you need to call replace(). The answers given were right.

But there was one more error in my code. You can't replace a fragment created statically in xml. So I changed

app_main_layout.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="fill_parent" android:layout_height="fill_parent"
  android:orientation="vertical" android:id="@+id/fragment_container">

</LinearLayout>

and

AppMainFragmentActivity.java

public class AppMainFragmentActivity extends FragmentActivity {

    @Override
    protected void onCreate(Bundle arg0) {
        super.onCreate(arg0);
        setContentView(R.layout.app_main_layout);

        FragmentManager fragmentManager = getSupportFragmentManager();
        FirstFragment fragment = new FirstFragment();
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
        fragmentTransaction.add(R.id.fragment_container,fragment);
        fragmentTransaction.commit();           
    }
}

Have you tried using ft.replace(R.id.fragment_container, fragment) instead of add ? add will not remove the existing fragment.

You are trying to add one more fragment in fragment_container, It is adding but your fragment wont visible because you have specified width and height for id_first_fragment as fill_parent so try to set wrap_content for id_first_fragment fragment . you can see the next fragment when you click on button . If you want to close first fragment and show second one you need to replace instead of add .

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!