سؤال

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.

هل كانت مفيدة؟

المحلول

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.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top