如何Android在设置elevation的情况下,再在上面覆盖控件

本文介绍如何在Android中创建一个有圆角和阴影的布局,并在其上覆盖图片。通过使用ConstraintLayout、自定义Drawable实现圆角以及利用elevation属性添加阴影。遇到底层布局覆盖图片的问题时,可以通过调整TranslateZ属性解决,实现图片位于底层布局之上。

我们产品设计师出了一个非常复杂的界面。在有圆角和阴影的布局上面覆盖一个图片,并且图片要超出下层布局。

在这里插入图片描述

设计

因为红色区域的图片要超出绿色的布局。所以我们在这2个控件的上面再添加一个布局,父布局包含这2个控件。由于他们是相对位置,使用相对布局比较合适。而RelativeLayout的替代者非ConstraintLayout莫属。绿色部分的底层布局需要圆角,我们可以自己编写一个Drawable 文件,实现圆角功能。另外需要阴影,那么使用elecation属性就可以了。黄色的文字部分直接放到绿色底层布局中。
如果按照上面的步骤编写,那么你会发现,绿色底层布局会覆盖红色图片。解决这个问题是我们使用TranslateZ属性,此属性是表示布局再Z周方向上的位置。我们设置一个正数,让他再绿色底层布局的上面。

在这里插入图片描述
大概能做出上面的效果。

代码
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="@dimen/x24"
        android:layout_marginTop="@dimen/x48"
        android:src="@mipmap/ico_stranger"
        android:translationZ="24dp"
        app:layout_constraintStart_toStartOf="@+id/rll_view_bottom"
        app:layout_constraintTop_toTopOf="parent" />

    <com.app.common.commonwidget.roundview.RoundLinearLayout
        android:id="@+id/rll_view_bottom"
        android:layout_width="@dimen/x540"
        android:layout_height="@dimen/x300"
        android:layout_marginTop="@dimen/x60"
        android:elevation="@dimen/x24"
        android:gravity="center"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:rv_cornerRadius="@dimen/x24"
        app:rv_strokeColor="@color/E1E1E1"
        app:rv_strokeWidth="@dimen/x3">

        <TextView
            style="@style/text_mw_ff323232_text_14"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="你好嘛!" />
    </com.app.common.commonwidget.roundview.RoundLinearLayout>
</android.support.constraint.ConstraintLayout>

尾声

要实现复杂布局是需要一些思考的,还要掌握布局的特别属性。如果情非得已,不要去自定义view重写里面的onmeasure,onlayout,ondraw方法,因为这样效率不高,还很容易出错误。比如我们经常用到图片周围显示文字,这种情况其实只需要一个textview就可以搞定。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值