为什么隐藏片段会导致空指针异常?

时间:2017-10-14 19:26:20

标签: android android-fragments kotlin

更新1:

我看到this answer解决了这个问题,但我不明白为什么和feel like this guy

这两个都返回非空的InfoboxFragments,但事务失败,第一个

childFragmentManager.findFragmentById(R.id.infobox_fragment)
childFragmentManager.findFragmentByTag("plz")

对不起?!

更新2:

childFragmentManager对xml中的嵌套片段不起作用。

我一直在试图将片段隐藏在另一个片段中一段时间​​。我已经尝试了一些方法,将子片段高度减少到1dp似乎是最可靠的,但它留下了一些片段可见

所以,我尝试了一种推荐的方法,即将childFragmentManager与事务一起使用来隐藏片段,如下所示。

Android文档说明了hide(fragment)方法:

  

隐藏现有片段。这仅适用于其片段   视图已添加到容器中,因为这将导致视图   隐藏

所以,我已将该片段包含在LinearLayout内。

showInfoBox()工作正常但hideInfoBox()与NPE崩溃:

java.lang.NullPointerException: Attempt to invoke virtual method 'void android.view.ViewGroup.startViewTransition(android.view.View)' on a null object reference
                                                                                          at android.support.v4.app.FragmentManagerImpl.completeShowHideFragment(FragmentManager.java:1681)
                                                                                          at android.support.v4.app.FragmentManagerImpl.moveFragmentToExpectedState(FragmentManager.java:1778)

唯一的区别似乎是hideshow次交易。

    private fun showInfoBox() {
        val infoboxFragment = childFragmentManager.findFragmentById(R.id.infobox_fragment) as InfoboxFragment

        childFragmentManager.beginTransaction()
                .setCustomAnimations(android.R.animator.fade_in,
                        android.R.animator.fade_out)
                .show(infoboxFragment)
                .commit()

        TransitionManager.beginDelayedTransition(constraintLayout)
        applyConstraintSet.applyTo(constraintLayout)

    }

    private fun hideInfoBox() { // this crashes
        val infoboxFragment = childFragmentManager.findFragmentById(R.id.infobox_fragment) as InfoboxFragment

        childFragmentManager.beginTransaction()
                .setCustomAnimations(android.R.animator.fade_in,
                        android.R.animator.fade_out)
                .hide(infoboxFragment) // with only this difference
                .commit()
    }

片段的添加如下:

override fun onViewCreated(view: View?, savedInstanceState: Bundle?) {
    super.onViewCreated(view, savedInstanceState)

    val infoboxFragment = InfoboxFragment()
    with(childFragmentManager) {
        beginTransaction().add(R.id.infobox_fragment_container, infoboxFragment).commit()
        //beginTransaction().hide(infoboxFragment).commit()
    }

    resetConstraintSet.clone(constraintLayout)
    applyConstraintSet.clone(constraintLayout)
    //applyConstraintSet.setVisibility(R.id.infobox_fragment_container, View.VISIBLE)
    applyConstraintSet.constrainHeight(R.id.infobox_fragment_container, 250.toDP())
}

0 个答案:

没有答案
相关问题