Android fragments overlap

自闭症网瘾萝莉.ら 提交于 2020-01-11 13:03:44

问题


I have an activity with two fragments, one to display a list and one to show the details of the clicked item. When starting the app the detail part is something static, once I click an item it should get replaced. The problem is that the old fragment is not being replaced, so both views are on top of each other.

My activity layout is:

<?xml version="1.0" encoding="utf-8"?>

<fragment
    android:id="@+id/listFragment"
    android:layout_width="0dp"
    android:layout_height="match_parent"
    android:layout_weight="1"
    class="com.fragments.FragmentOrderList" >
</fragment>

<fragment
    android:id="@+id/detailFragment"
    android:layout_width="0dp"
    android:layout_height="match_parent"
    android:layout_weight="2"
    class="com.fragments.FragmentOrderDetails" >

</fragment>

The layout for the detail fragment is:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent" >


<TextView
    android:id="@+id/tvOrderDetail"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="test view of details fragment" >
</TextView>

And in the above layout we see as well the static text we see initially. The code in my activity to replace the fragment is this

        FragmentTransaction transaction = getFragmentManager().beginTransaction();
    FragmentOrderDetails newFragment = new FragmentOrderDetails();
    newFragment.setArguments(b);
    transaction.replace(R.id.detailFragment, newFragment);

    transaction.addToBackStack(null);
    transaction.commit();

To me it looks like it is not a "replace" but rather an "add". Do I have to remove the old fragment always? Or do I have to follow a different approach here? It seems to me that only the original fragment stays there and on the second, third, ... replace the previous fragment is replaced correctly, just the static one stays there at all times.


回答1:


Instead of using in layout xml fragment:

<fragment
    android:id="@+id/detailFragment"
    android:layout_width="0dp"
    android:layout_height="match_parent"
    android:layout_weight="2"
    class="com.fragments.FragmentOrderDetails" >

</fragment>

Use some container like LinearLayout or FrameLayout with some containerId. Then programatically firstly add fragment to this container using containerId, and after that replace content of this container with containerId also.



来源:https://stackoverflow.com/questions/21638566/android-fragments-overlap

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