如何用LayoutInflater将新视图置于根视图顶部?Button遮挡问题
我来帮你搞定这个头疼的问题!你遇到的情况其实是Android Material Design组件的一个小特性导致的:Button作为Material风格的控件,默认带有elevation(阴影高度/Z轴值),而你添加的全屏InfoDialog是普通的RelativeLayout子类,默认Z轴值为0,所以即使你把它添加到根布局、调用bringToFront(),Button的Z轴优先级更高,还是会显示在最上层。
几个不用包裹Button的解决方案:
方案1:给InfoDialog设置更高的elevation
直接在你的InfoDialog的XML布局里添加android:elevation属性,值比Button默认的高就行(Button默认elevation大概是2dp,设置16dp肯定足够):
<?xml version="1.0" encoding="utf-8"?> <com.sseo242.airua.CustomViews.InfoDialog xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:background="@color/semiBlack" android:focusable="true" android:clickable="true" android:elevation="16dp"> <!-- 新增这一行 --> <LinearLayout android:id="@+id/dialog_board" android:layout_width="300dp" android:layout_height="wrap_content" android:layout_centerInParent="true" android:orientation="vertical" android:gravity="center" android:background="@drawable/dialog_background"> <!-- 你的其他控件 --> </LinearLayout> </com.sseo242.airua.CustomViews.InfoDialog>
方案2:在代码中设置InfoDialog的Z值
如果不想修改XML,也可以在Java代码中动态设置更高的Z值:
// 获取根布局 RelativeLayout rootView = findViewById(R.id.root_view); // 填充新视图 InfoDialog infoDialog = (InfoDialog) LayoutInflater.from(this) .inflate(R.layout.your_info_dialog_layout, rootView, false); // 设置比Button更高的Z值 infoDialog.setZ(20f); // 添加到根布局 rootView.addView(infoDialog);
方案3:关闭Button的elevation(不推荐)
你也可以给所有Button添加android:elevation="0dp",但这样会丢失Button的Material阴影效果,破坏设计风格,不太建议这么做。
为什么包裹LinearLayout能解决问题?
当你把Button放进LinearLayout后,Button的elevation是相对于它的父布局LinearLayout的,而LinearLayout本身的默认Z值是0,和你的全屏InfoDialog一致。这时候视图的绘制顺序就起作用了——你添加的InfoDialog在根布局的最后,所以会覆盖LinearLayout及其内部的Button。
内容的提问来源于stack exchange,提问作者Son Nguyen
相关产品推荐
相关产品推荐

