android - android 中的 fragment 事务导致黑屏

标签 android android-layout android-fragments

如果有帮助,我想要的与此google tutorial中所做的类似

但是在转换之前创建了一个 fragment 。如果我这样做,过渡效果很好;但我不能使用这种方法

=====

针对 API 7+ 我只是想让一个 fragment 在整个屏幕上可见并使用一个按钮(一个绘制的按钮,带有一个 onTouch 事件)然后切换到第二个 fragment ,反之亦然。

但是,当我用第二个 fragment 替换第一个 fragment 时,或者如果我使用 fragmentTransaction.show 和 fragmentTransaction.hide,我会得到一个空白屏幕;在出现黑屏之前,我可以切换两次。我不想在 backstack 上。

我在 MainActivity 的 onCreate 中创建 fragment :

DiceTable diceTable = new DiceTable();
Logger logger = new Logger();
fragmentTransaction.add(diceTable, DICETABLE_TAG);
fragmentTransaction.add(logger, LOGGER_TAG);
fragmentTransaction.add(R.id.fragment_container, logger);
fragmentTransaction.add(R.id.fragment_container, diceTable);

然后在一种方法(从 fragment 中调用)上进行切换:

    Logger logger = (Logger)fragmentManager.findFragmentByTag(LOGGER_TAG);
    DiceTable diceTable = (DiceTable)fragmentManager.findFragmentByTag(DICETABLE_TAG);

    if (diceTable.isVisible()) {
        fragmentTransaction.replace(R.id.fragment_container, logger);

        fragmentTransaction.commit();
        fragmentTransaction.hide(diceTable);
        fragmentTransaction.show(logger);
    }
    else if (logger.isVisible()) {
        fragmentTransaction.replace(R.id.fragment_container, diceTable);

        fragmentTransaction.commit();
        fragmentTransaction.hide(logger);
        fragmentTransaction.show(diceTable);
    }

这不是我应该怎么做吗?

替换 fragment 时黑屏

最佳答案

尝试以这种方式初始化 fragment :

private void initFragments() {
    mDiceTable = new DiceTable();
    mLogger = new Logger();
    isDiceTableVisible = true;

    FragmentManager fm = getSupportFragmentManager();
    FragmentTransaction ft = fm.beginTransaction();
    ft.add(R.id.fragment_container, mDiceTable);
    ft.add(R.id.fragment_container, mLogger);
    ft.hide(mLogger);
    ft.commit();
}

然后以这种方式在它们之间翻转:

 private void flipFragments() {
        FragmentManager fm = getSupportFragmentManager();
        FragmentTransaction ft = fm.beginTransaction();
        if (isDiceTableVisible) {
            ft.hide(mDiceTable);
            ft.show(mLogger);
        } else {
            ft.hide(mLogger);
            ft.show(mDiceTable);
        }
        ft.commit();
        isDiceTableVisible = !isDiceTableVisible;
    }

关于android - android 中的 fragment 事务导致黑屏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16546098/

相关文章:

android - 不登录显示个人资料图片

android - Google Play Services 9.2.0 导致设备在没有 Google Play Services 的情况下意外崩溃 - NPE at android.app.Instrumentation.execStartActivity

java - Android EditText问题findviewbyId

Android ActionBarSherlock 选项卡、Android 2.3 或更低版本上的 NoClassDefFoundError

android - 如何将数据加载到 ListFragment?

java - 如何在 Android Google Maps v2 中创建带有传感器方位的位置箭头标记?

java - 不希望 Listactivity 的项目之间存在距离

java - onActivityResult()之后动态添加的imageView消失

android - onMeasure 被调用 1,500 多次

Android Fragment 返回不起作用,setDisplayHomeAsUpEnabled(true)setHomeButtonEnabled(true);