用另一个片段替换一个片段

San*_*anu 9 android android-layout android-fragments

我想Fragment用新的替换旧的Fragment,但我仍然得到旧的按钮,Fragment在新片段中仍然可见.

在旧的,按一下按钮 在此输入图像描述

FragmentTransaction transaction = getFragmentManager().beginTransaction();
Fragment newFragment = GenericMood.newInstance("a","b");

// Replace whatever is in the fragment_container view with this fragment,
// and add the transaction to the back stack if needed
transaction.replace(R.id.allmoods, newFragment);
transaction.addToBackStack(null);
transaction.commitAllowingStateLoss();
Run Code Online (Sandbox Code Playgroud)

我可以用Fragment新的替换旧的,但是R.id.allmoods的按钮Fragment仍然可以在新的顶部看到Fragment.

在此输入图像描述

我尝试使用下面给出的代码.

FragmentTransaction transaction = getFragmentManager().beginTransaction();
Fragment newFragment = GenericMood.newInstance("a","b");

// Replace whatever is in the fragment_container view with this fragment,
// and add the transaction to the back stack if needed
transaction.replace(((ViewGroup)getView().getParent()).getId(), newFragment);
transaction.addToBackStack(null);
transaction.commitAllowingStateLoss();
Run Code Online (Sandbox Code Playgroud)

XML文件:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/allmoods"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/colorPrimary"
    tools:context="com.moodoff.Moods">
     <Button
        android:text="Button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="64dp"
        android:id="@+id/btn_btn"
        android:height="80dp"
        android:width="100dp"
        android:onClick="putmeoff"
        android:layout_marginLeft="17dp"
        android:layout_marginStart="17dp"/>
</RelativeLayout>
Run Code Online (Sandbox Code Playgroud)

这是应该取代上述的片段:

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:id="@+id/genericmood"
    android:layout_height="match_parent"
    android:background="@color/colorPrimary"
    tools:context="com.moodoff.GenericMood">
    <!-- TODO: Update blank fragment layout -->


    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="#000000"
        android:layout_gravity="fill_horizontal"
        android:id="@+id/floatingButtons"
        >
        <android.support.design.widget.FloatingActionButton
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="1dp"
            android:layout_marginRight="14dp"
            app:backgroundTint="#ffffff"
            android:layout_alignParentTop="true"
            android:layout_alignParentRight="true"
            android:layout_alignParentEnd="true"
            android:src="@drawable/cameraicon"
            android:id="@+id/btn_camera"
            app:fabSize="mini"
            />
    </RelativeLayout>
</FrameLayout>
Run Code Online (Sandbox Code Playgroud)

两者都不起作用.该怎么办? 更新:用适当的容器替换后,按钮已经消失,但新片段没有得到正确的实例化.我得到一个纯白色的空白屏幕. 在此输入图像描述

my activity_alltabs.xml looks like this: 

<?xml version="1.0" encoding="utf-8"?>
    <android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        xmlns:tools="http://schemas.android.com/tools"
        android:id="@+id/main_content"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:fitsSystemWindows="true"
        tools:context="com.moodoff.AllTabs">

        <android.support.design.widget.AppBarLayout
            android:id="@+id/appbar"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:theme="@style/AppTheme.AppBarOverlay">

            <android.support.design.widget.TabLayout
                android:id="@+id/tabs"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:background="@android:color/background_dark" />

        </android.support.design.widget.AppBarLayout>

        <android.support.v4.view.ViewPager
            android:id="@+id/container"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            app:layout_behavior="@string/appbar_scrolling_view_behavior" />

    </android.support.design.widget.CoordinatorLayout>
Run Code Online (Sandbox Code Playgroud)

Raj*_*eev 5

我以前曾经处理过碎片,并希望这会帮助你,让你更好地了解流程.首先,您的MainActivity.xml文件将如下所示:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
   xmlns:app="http://schemas.android.com/apk/res-auto"
   xmlns:tools="http://schemas.android.com/tools"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   app:layout_behavior="@string/appbar_scrolling_view_behavior"
   tools:context="com.example.activity.HomeActivity">


    //This frameLayout will contain all your fragments view.
   <FrameLayout
      android:id="@+id/container_view"
      android:layout_width="match_parent"
      android:layout_height="match_parent">
    </FrameLayout>

 </RelativeLayout>
Run Code Online (Sandbox Code Playgroud)

接下来,您将创建两个片段,并在下面提到它们的XML: fragment1.xml

<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"
    android:clickable="true" // important to have this
    tools:context=".fragments.frament1">

     <Button
        android:id="@+id/btn"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom"/>

 </RelativeLayout>
Run Code Online (Sandbox Code Playgroud)

下一个片段看起来与上面提到的完全相同.这是Fragment1.class:

public class Fragment1 extends Fragment implements View.OnClickListener {
Button btn;

   public Fragment1() {
    // Required empty public constructor
}

     @Override
     public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment1, container, false);
        view.setBackgroundColor(Color.WHITE);

       //Perform required conditions and return view 
       button = (Button) view.findViewById(R.id.btn);
       button.setOnClickListener(this);

       return view;
      }

        public void onClick(View v) {

             switch(v.getId())
             {
                case R.id.btn: 
                 //replace current fragment on button click

                 Fragment fragment2= new Fragment2();

                 getFragmentManager().beginTransaction().
                 replace(R.id.container_view, fragment2).
                 addToBackStack("frags").commit();

               break;
             }
        }
 }
Run Code Online (Sandbox Code Playgroud)

Fragment2如下:

 public class Fragment2 extends Fragment{
 String TAG = "Fragment2";


     public Fragment2() {
      // Required empty public constructor
   }

     @Override
     public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {

          View view = inflater.inflate(R.layout.fragment2,container,false);
          view.setBackgroundColor(Color.WHITE);
       return view;
    }
}
Run Code Online (Sandbox Code Playgroud)

正如我之前提到的,xml文件与fragment1.xml.更重要的是,主要活动将包含一个布局,当用户切换片段时,该布局将采用片段视图.因此我们使用replace方法,它只是用我们指定的片段视图替换前一个视图.


Mik*_*ike 3

在您的 Activity 的 onCreate 函数中,您应该调用setContentView(R.layout.main),然后当您想要加载 Fragment 时,您在 中选择一个 ViewParent R.layout.main。该片段将成为该 ViewParent 的子级。所以传入FragmentTransaction.replace 的id是 中 ViewParent 的 id R.layout.main

allmoodsrelativelayout 中的 Button 会保留,这是有道理的,因为FragmentTransaction.replace函数仅替换该容器中的现有片段。里面的一切都R.layout.main将保留。这就是活动保存静态内容(如抽屉或工具栏)的方式。

当您加载“新片段”时,您将使用相同的 ID。因此,“新片段”将替换“旧片段”,作为 中 ViewParent 的新子级R.layout.main

这是Fragments API 指南

更新:

当您在 Activity 的onCreate函数中调用FragmentTransaction.replace时,这可能会重新创建现有的 Fragment。确保savedInstanceState(传递给onCreate的Bundle)为空。如果savedInstanceState不为null,那么该片段可能已经存在,你可以这样找到它;

Fragment f = getFragmentManager().findFragmentByTag(YOUR_FRAGMENT_TAG);
Run Code Online (Sandbox Code Playgroud)

更新2:

这是一份应该对您有帮助的指南。看起来您可以使用FragmentPagerAdapter来简化片段事务。