Android中弹窗LinearLayout与按钮重叠,如何隐藏按钮使其置于后方?
解决Android布局重叠:让弹窗遮挡按钮的方法
嘿,看来你在布局层级的问题上卡壳啦!别着急,这个问题本质就是视图绘制优先级的事儿——我们只需要调整红色按钮和蓝色ShopL的层级关系,就能让弹窗稳稳盖在按钮上面。
方法一:调整XML中的布局顺序
在Android的布局系统里,父布局中后声明的视图会被绘制在更上层。所以如果你的按钮和ShopL是同级的ConstraintLayout子视图,直接把ShopL的代码放在按钮的后面就行:
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent"> <!-- 先声明红色按钮,它会被绘制在底层 --> <Button android:id="@+id/upg" android:layout_width="wrap_content" android:layout_height="wrap_content" android:background="@color/red" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" /> <!-- 后声明ShopL,它会自动覆盖在按钮上层 --> <LinearLayout android:id="@+id/ShopL" android:layout_width="match_parent" android:layout_height="match_parent" android:background="@color/blue" android:visibility="gone" <!-- 默认隐藏,点击按钮再设置为visible --> app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" /> </android.support.constraint.ConstraintLayout>
方法二:用elevation属性强制设置层级
如果布局顺序不好调整(比如ShopL是动态添加的),可以通过elevation(海拔)属性来控制视图的层级——值越大,视图越靠上。
给ShopL设置比按钮更高的elevation:
<LinearLayout android:id="@+id/ShopL" ... android:elevation="8dp" />
或者在代码里动态设置:
// Java代码 findViewById(R.id.ShopL).setElevation(8f); // Kotlin代码 findViewById<LinearLayout>(R.id.ShopL).elevation = 8f
只要保证按钮的elevation小于这个值(默认按钮的elevation一般是2dp左右),ShopL就会稳稳覆盖在按钮上面啦。
最后别忘了,点击按钮显示ShopL的时候,要把它的可见性从gone或者invisible改成visible哦!
内容的提问来源于stack exchange,提问作者Daniel Aleksandrov
相关产品推荐
相关产品推荐

