我想在某些片段中隐藏bottomNavigationView。
我尝试了以下代码,但具有闪烁效果。 (bottomNavigationView在nextFragment可见之前隐藏。
val navController = this.findNavController(R.id.nav_host_home)
navController.addOnDestinationChangedListener { _, destination, _ ->
when (destination.id) {
R.id.searchArticlesFragment -> bnvMain.visibility = View.GONE
R.id.articleFragment -> bnvMain.visibility = View.GONE
else -> bnvMain.visibility = View.VISIBLE
}
}
我也尝试了另一个代码。但是它会调整片段的大小。并在目标片段中给出OutOfMemoryException。
supportFragmentManager.registerFragmentLifecycleCallbacks(object :
FragmentManager.FragmentLifecycleCallbacks() {
override fun onFragmentViewCreated(
fm: FragmentManager,
f: Fragment,
v: View,
savedInstanceState: Bundle?
) {
when (f) {
is SearchArticlesFragment -> bnvMain.visibility = View.GONE
is ArticleDetailsFragment -> bnvMain.visibility = View.GONE
else -> bnvMain.visibility = View.VISIBLE
}
}
}, true)
请帮助我如何以正确且最佳的方式隐藏bottomNavigationView?这是我可以隐藏bottomNavigationView的唯一方法吗? youtube和Instagram如何实现这种行为?
答案 0 :(得分:2)
如果您的代码遵循单一活动设计模式,则以下解决方案适合您。
示例: 在parentAcitivty布局中,文件添加bottomNavigationView
<com.google.android.material.bottomnavigation.BottomNavigationView
android:id="@+id/main_bottom_navigation_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="?android:attr/windowBackground"
app:labelVisibilityMode="labeled"
app:menu="@menu/main_nav" />
步骤1:在父级活动中,创建一种更改可见性的方法。
fun setBottomNavigationVisibility(visibility: Int) {
// get the reference of the bottomNavigationView and set the visibility.
activityMainBinding.mainBottomNavigationView.visibility = visibility
}
第2步,第3步和第4步:
abstract class BaseFragment : Fragment() {
protected open var bottomNavigationViewVisibility = View.VISIBLE
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
// get the reference of the parent activity and call the setBottomNavigationVisibility method.
if (activity is MainActivity) {
var mainActivity = activity as MainActivity
mainActivity.setBottomNavigationVisibility(bottomNavigationViewVisibility)
}
}
override fun onResume() {
super.onResume()
if (activity is MainActivity) {
mainActivity.setBottomNavigationVisibility(bottomNavigationViewVisibility)
}
}
}
第5步:
class SampleFragment1 : BaseFragment() {
// set the visibility here, it takes care of setting the bottomNavigationView.
override var navigationVisibility = View.VISIBLE
// override var navigationVisibility = View.GONE
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_sampleFragment1, container, false)
}
}