我的 MainActivity
中有一个按钮可以打开 FragmentA
。 FragmentA
覆盖了整个屏幕,但我仍然看到 MainActivity
中的按钮,并且仍然可以单击它。
我尝试在 fragment 布局中使用 clickable
但它不起作用
主要 Activity
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
内。
当您将 fragment 添加
到容器中时,就像您正在做的那样,它只是以与View
相同的方式添加它。
因此,如果您将 Fragment 添加到已拥有 Button
作为子项的 ConstraintLayout
中,则该 Fragment 将与 Button
一起显示> 由于 ConstraintLayout
允许重叠 View 。
这也是为什么,如果您的容器是 LinearLayout
,那么添加 Fragment 会将 fragment 放置在 Button
下方。
因此,考虑到这一点,解决方案就是像处理 View 一样处理它。
如果您将一个 View 添加到布局中,并且另一个 View 重叠,您将如何摆脱它?
最常见的解决方案是在添加 fragment 时将按钮的可见性设置为“不可见”或“消失”。
另一个解决方案可能是提高 Fragment 的高度,使其现在高于您的 Button
。
当然,您也可以从Container中删除按钮并将其放入Fragment中。
这样,您就可以使用 FragmentManager
中的 replace()
方法将包含 Button
的 Fragment 替换为 您想要显示的 fragment
。
关于java - 单击 Fragment 会在 Activity 中进行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54658740/