如何在单个Activity中使用双ViewBinding并修复BottomSheet异常
问题根源
你当前的代码存在重复添加BottomSheet布局的问题:
- activity_main.xml已经通过
<include>标签引入了item_bottom_sheet布局 - 但在MainActivity里又通过
ItemBottomSheetBinding.inflate(..., binding.root, true)手动将该布局再次添加到CoordinatorLayout中
这会导致界面上存在两个BottomSheet实例,BottomSheetBehavior控制的是手动添加的那个,而include的实例也会占用布局空间,最终引发显示异常。
解决方案
步骤1:给include标签添加id
修改activity_main.xml中的include标签,增加唯一id,方便通过ViewBinding获取绑定实例:
<include android:id="@+id/bottom_sheet_include" layout="@layout/item_bottom_sheet" />
步骤2:修改MainActivity代码,复用已include的布局绑定
删除手动inflateItemBottomSheetBinding的代码,改用bind()方法获取已存在于布局树中的BottomSheet绑定:
class MainActivity : AppCompatActivity() { private lateinit var binding : ActivityMainBinding private lateinit var bottomSheetBinding: ItemBottomSheetBinding private lateinit var bottomSheetBehavior: BottomSheetBehavior<*> override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityMainBinding.inflate(LayoutInflater.from(this)) setContentView(binding.root) // 绑定已通过include引入的BottomSheet布局 bottomSheetBinding = ItemBottomSheetBinding.bind(binding.bottomSheetInclude.root) bottomSheetBehavior = BottomSheetBehavior.from(bottomSheetBinding.bottomSheet) bottomSheetBehavior.peekHeight = 0 bottomSheetBehavior.state = BottomSheetBehavior.STATE_COLLAPSED binding.expand.setOnClickListener { bottomSheetBehavior.state = BottomSheetBehavior.STATE_EXPANDED } binding.collapse.setOnClickListener { bottomSheetBehavior.state = BottomSheetBehavior.STATE_COLLAPSED } bottomSheetBinding.btnCancel.setOnClickListener { Toast.makeText(this, "xczc", Toast.LENGTH_SHORT).show() } } }
原理说明
ItemBottomSheetBinding.bind(view)方法会复用布局树中已存在的View实例生成绑定对象,不会重复创建和添加View- 这样BottomSheetBehavior就会绑定到
<include>引入的那个唯一BottomSheet实例上,和用findViewById的逻辑一致,从而恢复正常的展开/收起行为
内容的提问来源于stack exchange,提问作者Super Hoang
相关产品推荐
相关产品推荐

