CardView设clickable=true时,如何阻止SeekBar获焦且屏蔽MapView点击?
问题
在MapView上方放置了一个CardView,为避免点击CardView时触发MapView的拖拽操作,给CardView设置了android:clickable="true"属性。但此时点击CardView的任意区域,其内部的SeekBar都会自动获取焦点。需要实现:点击CardView时既屏蔽MapView的响应,又不让SeekBar获取焦点。
原布局代码:
<androidx.cardview.widget.CardView android:id="@+id/cardview" android:layout_width="0dp" android:layout_height="0dp" android:layout_marginStart="12dp" android:layout_marginTop="4dp" android:layout_marginBottom="12dp" android:clickable="true" android:visibility="visible" app:cardBackgroundColor="@color/darkGray" tools:ignore="MissingConstraints"> <SeekBar android:id="@+id/seekbar" android:layout_width="0dp" android:layout_height="20dp" android:max="360" android:progressBackgroundTint="@color/white" android:progressTint="@color/white" /> </androidx.cardview.widget.CardView>
解决方案
方法一:通过布局属性直接控制
调整CardView和SeekBar的焦点相关属性,从布局层面解决问题:
- 给CardView添加
android:focusable="true"和android:focusableInTouchMode="true",让CardView在触摸时优先获取焦点,阻止内部SeekBar自动抢焦点 - 给SeekBar设置
android:focusable="false",禁止其主动获取焦点 - 保留
android:clickable="true"确保屏蔽MapView的拖拽响应
修改后的布局代码:
<androidx.cardview.widget.CardView android:id="@+id/cardview" android:layout_width="0dp" android:layout_height="0dp" android:layout_marginStart="12dp" android:layout_marginTop="4dp" android:layout_marginBottom="12dp" android:clickable="true" android:focusable="true" android:focusableInTouchMode="true" android:visibility="visible" app:cardBackgroundColor="@color/darkGray" tools:ignore="MissingConstraints"> <SeekBar android:id="@+id/seekbar" android:layout_width="0dp" android:layout_height="20dp" android:max="360" android:focusable="false" android:progressBackgroundTint="@color/white" android:progressTint="@color/white" /> </androidx.cardview.widget.CardView>
方法二:通过代码拦截点击事件
如果不想修改太多布局属性,可以在代码中给CardView设置空点击事件,拦截触摸事件:
// Kotlin示例 findViewById<CardView>(R.id.cardview).setOnClickListener { // 空实现,仅用于拦截事件 }
// Java示例 CardView cardView = findViewById(R.id.cardview); cardView.setOnClickListener(v -> { // 空实现,仅用于拦截事件 });
这样点击CardView时,事件会被CardView消费,既不会传递给MapView,也不会触发内部SeekBar获取焦点。
内容的提问来源于stack exchange,提问作者Komal Sharma
相关产品推荐
相关产品推荐

