当前位置: 代码迷 >> java >> 在“活动”中单击“片段”
  详细解决方案

在“活动”中单击“片段”

热度:86   发布时间:2023-07-31 10:57:30.0

我的MainActivity中有一个打开FragmentA的按钮。 FragmentA覆盖了整个屏幕,但是我仍然看到MainActivity的按钮,并且仍然可以单击它。

我已尝试在片段布局中使用clickable ,但无法正常工作

主活动

override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        button.setOnClickListener {
            val fragmentManager = this@MainActivity.supportFragmentManager
            fragmentManager.beginTransaction()
                .add(R.id.fragment_container, AFragment())
                .addToBackStack(null)
                .commit()
        }
    }

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context=".MainActivity"
        android:id="@+id/fragment_container">

    <Button
            android:text="Button Main"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/button" app:layout_constraintTop_toTopOf="parent"
            app:layout_constraintStart_toStartOf="parent" app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintEnd_toEndOf="parent"/>
</android.support.constraint.ConstraintLayout>

fragment_a.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:layout_width="match_parent"
              android:layout_height="match_parent"
              android:clickable="true"
              android:focusable="true">
              android:background="@color/colorPrimary"
    <TextView
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:text="A"/>

</LinearLayout>

发生这种情况是因为您将Button放置在您用作Fragment容器的ConstraintLayout内。

当您像正在做的那样add片段add到容器中时,它只是以类似于View方式add片段。

因此,如果将片段添加到已经拥有子ButtonConstraintLayout中,则由于ConstraintLayout允许重叠视图,因此该片段将与Button一起显示。

这就是为什么如果您的容器是LinearLayout ,那么添加一个Fragment会将该片段放置在Button下方的原因。

因此,考虑到这一点,解决方案就是像对待视图一样处理它。

如果将视图添加到布局中,并且另一个视图重叠,那么如何摆脱它呢?

最常见的解决方案是在添加片段时将Button的可见性设置为INVISIBLE或GONE。

另一个解决方案可能是提高Fragment的高度,因此它现在比Button

当然,您也可以从“容器”中删除按钮并将其也放置在“片段”中。

这样,您可以在FragmentManager使用replace()方法将包含您的ButtonFragment替换为您想要显示的Fragment

  相关解决方案