问题描述
我的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>
1楼
发生这种情况是因为您将Button
放置在您用作Fragment容器的ConstraintLayout
内。
当您像正在做的那样add
片段add
到容器中时,它只是以类似于View
方式add
片段。
因此,如果将片段添加到已经拥有子Button
的ConstraintLayout
中,则由于ConstraintLayout
允许重叠视图,因此该片段将与Button
一起显示。
这就是为什么如果您的容器是LinearLayout
,那么添加一个Fragment会将该片段放置在Button
下方的原因。
因此,考虑到这一点,解决方案就是像对待视图一样处理它。
如果将视图添加到布局中,并且另一个视图重叠,那么如何摆脱它呢?
最常见的解决方案是在添加片段时将Button的可见性设置为INVISIBLE或GONE。
另一个解决方案可能是提高Fragment的高度,因此它现在比Button
。
当然,您也可以从“容器”中删除按钮并将其也放置在“片段”中。
这样,您可以在FragmentManager
使用replace()
方法将包含您的Button
的Fragment
替换为您想要显示的Fragment
。