我的 Activity 有3个 fragment ; header ; body ;页脚(与HTML相同)。主体 fragment 包含三个按钮,每个按钮应将中间 fragment (主体;本身)替换为另一个按钮,但是在此我无法弄清楚如何使用FragmentManager和FragmentTransition。在其他人关于其他人实现其 fragment 的方式的问题上,我似乎找不到任何连贯性。似乎每个人都有自己的方法,或者只是没有在其线程中包含完整的代码。

MainActivity.java

public class MainActivity extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    this.requestWindowFeature(Window.FEATURE_NO_TITLE);
    this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN);
    setContentView(R.layout.test_frag);
}


@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}

}

TestFragment.java
public class TestFragment extends Fragment {

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

    return inflater.inflate(R.layout.test_frag, container, false);
}

}

BodyFragment.java
public class BodyFragment extends Fragment {

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

    return inflater.inflate(R.layout.body_frag, container, false);
}

}

XML中的 fragment
<fragment
    android:id="@+id/bodyfragment"
    android:name="com.example.test.BodyFragment"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_weight="1"
    tools:layout="@layout/body_frag" />

XML中的BodyFragment布局(按钮x3)
    <Button
    android:id="@+id/bsettings"
    android:layout_width="130dp"
    android:layout_height="40dp"
    android:layout_alignBaseline="@+id/bgames"
    android:layout_alignBottom="@+id/bgames"
    android:layout_toRightOf="@+id/bgames"
    android:text="SETTINGS" />

最佳答案

您可以像这样使用FragmentManager:

FragmentManager manager = getFragmentManager();
FragmentTransaction transaction = manager.beginTransaction();
transaction.replace(R.id.bodyfragment, AnotherFragment.newInstance()); // newInstance() is a static factory method.
transaction.commit();

此代码将用另一个Fragment的新实例替换ID为R.id.bodyfragment的View中的Fragment。

编辑:

为了创建另一个Fragment的新实例,应该使用静态工厂方法。您可以像这样在Fragment中实现它们:
public class AnotherFragment extends Fragment {

    public static AnotherFragment newInstance() {
        AnotherFragment fragment = new AnotherFragment();
        ...
        // do some initial setup if needed, for example Listener etc
        ...
        return fragment;
    }
    ...
}

10-04 23:09