如何Android在設置elevation的情況下,再在上面覆蓋控件

我們產品設計師出了一個非常複雜的界面。在有圓角和陰影的佈局上面覆蓋一個圖片,並且圖片要超出下層佈局。

在這裏插入圖片描述

設計

因爲紅色區域的圖片要超出綠色的佈局。所以我們在這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就可以搞定。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章