布局中Button始终在顶层无法被覆盖

最近写项目时遇到一个很奇怪的问题,在Relativelayout中Button始终在最顶层,无法被其他控件覆盖,然后试了下在Android 5.0以下的版本可以被正常覆盖,几经周折,终于找到了原因。

产生原因:stateListAnimator属性
谷歌在Material Design中推出,是一个非常简单的方法用来实现在可视状态之间平滑过渡。这个属性可以通过android:stateListAnimator进行设置,可以使控件在点击时产生不同的交互。对于Button,点击时默认有个阴影的效果用于表示按下的状态(5.0以前就是简单的变色)。
参考链接:android5.0 StateListAnimator

解决方法:

  1. 如果Button已经有自定义的selector样式而不需要原生的按下后的阴影效果,可以使用android:stateListAnimator="@null"去掉阴影效果而使Button可以被正常的覆盖
  2. 如果希望保留Button的阴影效果而又想使其能够被覆盖,则应该使用个单独的Linearlayout对Button进行包裹,记住要给Button的下方和左右侧留出空余。这种方法虽然不符合规范,但是为了需求只得这么做了。
    代码示例:
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="52dp">

	            <Button         
	            android:id="@+id/btn"
                android:layout_width="match_parent"
                android:layout_height="42dp"
                android:layout_marginLeft="30dp"
                android:layout_marginRight="30dp"
          android:background="@drawable/login_btn_selector"
                android:text="@string/app_login"
                tools:ignore="UselessParent"
                android:textColor="@color/white"
                android:textSize="20sp" />
        </LinearLayout>
  • 5
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
可以使用以下两种方法解决这个问题: 1. 在布局使用RelativeLayout,将Button放在RecyclerView之上,确保Button的z-index比RecyclerView高。 示例代码: ``` <RelativeLayout android:layout_width="match_parent" android:layout_height="match_parent"> <androidx.recyclerview.widget.RecyclerView android:id="@+id/recycler_view" android:layout_width="match_parent" android:layout_height="match_parent"/> <Button android:id="@+id/button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentBottom="true" android:layout_centerHorizontal="true" android:text="Button"/> </RelativeLayout> ``` 2. 使用CoordinatorLayout,将RecyclerView和Button放在不同的子视图,并使用app:layout_anchor属性将Button锚定在RecyclerView下方。 示例代码: ``` <androidx.coordinatorlayout.widget.CoordinatorLayout android:layout_width="match_parent" android:layout_height="match_parent"> <androidx.recyclerview.widget.RecyclerView android:id="@+id/recycler_view" android:layout_width="match_parent" android:layout_height="match_parent" app:layout_behavior="@string/appbar_scrolling_view_behavior"/> <Button android:id="@+id/button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="bottom|center_horizontal" android:text="Button" app:layout_anchor="@id/recycler_view" app:layout_anchorGravity="bottom"/> </androidx.coordinatorlayout.widget.CoordinatorLayout> ``` 这两种方法都可以让Button在RecyclerView之上,并且不会被RecyclerView覆盖。选择哪种方法取决于你的具体需求和布局结构。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值