代码之家  ›  专栏  ›  技术社区  ›  Tobias Reich

Android片段在弹出时重叠

  •  0
  • Tobias Reich  · 技术社区  · 7 年前

    我有一个片段容器,可以显示当前片段。当按下后退按钮时,我想删除最上面的片段,但当它是第一个片段时,我想在后台移动应用程序。(否则,我的主要片段也会被删除。)

    所以我的(Kotlin)代码看起来是这样的:

    override fun onBackPressed() {
        ...
        when (supportFragmentManager.backStackEntryCount) {
            1    -> {
                moveTaskToBack(true)
            }
            else -> {
               super.onBackPressed()
               //supportFragmentManager.popBackStackImmediate()
            }
        }
    

    只有一个例外。当我启动应用程序并显示第二个片段时,我按下后退按钮两次(快速)。这样,顶部碎片开始被移除,但第二次背压随后直接开始(顶部碎片没有完全移除)。 我还尝试使用supportFragmentManager。PopBackbackImmediate()代替,但它也不起作用。

    所以我有两个问题:

    • 之后如何继续清理(当应用程序再次可见时)

    • 或者,如果这不是解决方案,我如何检查FragementManager中是否仍有正在进行的片段事务(在第二次按下将应用程序放到后台之前)

    ----编辑1----

    我注意到只有在替换片段时设置事务动画时才会发生这种情况。因此,如果我在添加碎片时(而不是在反压时)删除该行,它似乎会起作用:

      ft.setCustomAnimations(R.anim.enter_from_bottom, R.anim.exit_to_top,
       R.anim.enter_from_top, R.anim.exit_to_bottom)
    

    ----编辑2----

    当在这里使用这段代码时,它也可以工作(只是区别在于它也删除了第一个(底部)片段)。但显然,原生Android方法似乎可以避免这个问题。

    super.onBackPressed() // Remove bottom fragement
    super.onBackPressed() // No more fragments -> move App into background
    

    ----这就是“创建”片段的方式----

    val ft = supportFragmentManager.beginTransaction()
    ft.setCustomAnimations(R.anim.enter_from_bottom, R.anim.exit_to_top, 
        R.anim.enter_from_top, R.anim.exit_to_bottom)
    ft.replace(R.id.fragmentContainer, fragment, fragment::class.java.simpleName)
        .addToBackStack(fragment::class.java.simpleName)
        .commitAllowingStateLoss()
    

    下面是重叠片段的屏幕截图:

    Screenshot of the overlapping Fragments

    0 回复  |  直到 7 年前
        1
  •  0
  •   Beto NaranjoF    7 年前

    试试这个。。。。

    使用FrameLayout创建xml

    android:background="#ffffff"
    

    在你所有的片段中加入。主视图组件上的xml,例如:

    <?xml version="1.0" encoding="utf-8"?>
    <android.support.constraint.ConstraintLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="#ffffff"
        xmlns:app="http://schemas.android.com/apk/res-auto">
    
        <TextView
            android:id="@+id/textView1"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginBottom="8dp"
            android:layout_marginEnd="8dp"
            android:layout_marginStart="8dp"
            android:layout_marginTop="8dp"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent" />
    
    </android.support.constraint.ConstraintLayout> 
    
    推荐文章