Android 控件描边、加阴影

一、描边

      最近,项目中有文本框需要四周加边框给把文字围起来。我想这不就是描边吗,即给控件设置边框样式(包括粗细、颜色、圆角等)

先上效果

于是在drawable中定义了edge.xml文件

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
    <!-- 这里是设置背景色-->
<!--    <solid android:color="@color/colorGrey" />-->
    <!-- 这里是设置为四周 也可以单独设置某个位置为圆角-->
    <corners android:topLeftRadius="5dp"
        android:topRightRadius="5dp"
        android:bottomRightRadius="5dp"
        android:bottomLeftRadius="5dp"/>
    <!-- 这里设置边框 -->
    <stroke android:width="1dp" android:color="#FFFFFFFF" />
</shape>

solid设置背景色,corners设置圆角,stroke设置边框颜色粗细。

然后直接在控件中使用即可:

<TextView
    android:id="@+id/connect_wifi"
    android:layout_width="60dp"
    android:layout_height="19dp"
    android:gravity="center"
    android:layout_gravity="center_vertical|center_horizontal"
    android:text="@string/andWiFi"
    android:background="@drawable/edge"
    android:layout_marginRight="29dp"
    android:textSize="12sp"
    android:textColor="@color/white">
</TextView>

二、加阴影

还有就是最近封装了一个自定义下拉框,很感兴趣的同学可以看我上篇博客。由于这个下拉框是叠加在其他控件上面的,类似于悬挂卡片。需要下拉框四周加阴影才更能把这种立体感体现出来。这里总结一下我亲测有效两种方式

先上图:

一种是直接在控件里加两种属性。

android:translationZ="1dp"

android:elevation="1dp"

如:

<LinearLayout-->
<!--                android:layout_width="210dp"-->
<!--                android:layout_height="wrap_content"-->
<!--                android:layout_gravity="top|right"-->
<!--                android:layout_marginTop="16dp"-->
<!--                android:layout_marginRight="30dp"-->
<!--                android:background="@color/white"-->
<!--                android:elevation="1dp"-->
<!--                android:orientation="vertical"-->
<!--                android:translationZ="1dp">-->

另一种是使用CardView

我看很多博主啰里啰嗦一大堆,没说到点子上  我直接上干货

<?xml version="1.0" encoding="utf-8"?>
<androidx.cardview.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="210dp"
    android:layout_height="wrap_content"
    android:background="@color/white"
    app:cardElevation="1dp">
...........................这里自由发挥,写上你需要填充控件...........................</androidx.cardview.widget.CardView>

直接在你写好的控件外边一层是ardView即可。cardElevation属性是设置阴影大小的,别忘了加入

xmlns:app="http://schemas.android.com/apk/res-auto"这行,否者没法用app属性。

猜你喜欢

转载自blog.csdn.net/weixin_54723630/article/details/126907993