动态替换片段?

时间:2018-04-22 08:15:00

标签: android android-fragments

现在我知道这是一个非常简单的问题并被多次询问,但之前提供的解决方案中没有一个对我有用。

我有一个FrameLayout活动,如下所示:

<android.support.constraint.ConstraintLayout 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"
    tools:context=".MainActivity">

    <FrameLayout
        android:id="@+id/replace_me"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent">

    </FrameLayout>

</android.support.constraint.ConstraintLayout>

在我的MainActivity课程中,我有以下内容:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    if (savedInstanceState == null) {
        replaceFragment(new ChooseLevelFragment(), false);
    }
}

public void replaceFragment(Fragment fragment, boolean addToBackStack) {
    FragmentTransaction replace = getSupportFragmentManager().beginTransaction().replace(R.id.replace_me, fragment);
    if (addToBackStack) {
        replace.addToBackStack(null);
    }
    replace.commit();
    Log.d(TAG, "Fragment replaced!");
}

第一个片段正确显示。但是,当用户从菜单中单击某个项目并登录时,应用程序应使用新的替换当前片段

private void showAuthenticationDialog() {
    FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();

    Fragment fragmentByTag = getSupportFragmentManager().findFragmentByTag(AuthenticationDialogFragment.TAG);

    if (fragmentByTag != null) {
        fragmentTransaction.remove(fragmentByTag);
    }
    fragmentTransaction.addToBackStack(null);

    AuthenticationDialogFragment authenticationDialogFragment = AuthenticationDialogFragment.newInstance(() -> {
        replaceFragment(new ParentControlPanelFragment(), true);
    });
    authenticationDialogFragment.show(fragmentTransaction, AuthenticationDialogFragment.TAG);

}

即使在提交之后,新片段也不会被替换。我可以看到我的日志消息,但不能看到新的片段。我不太确定问题出在哪里。

1 个答案:

答案 0 :(得分:0)

问题是我在解除对话之前试图替换片段。

正确的方法是首先关闭对话框然后尝试替换片段。

相关问题