如何在TextView中创建阴影?

时间:2018-01-22 18:15:29

标签: android android-layout layout textview

我有一个要求在TextView中创建阴影吗?

我怎样才能实现它?附加屏幕。

enter image description here

如果有任何想法,请告诉我。

谢谢!提前。

2 个答案:

答案 0 :(得分:2)

在XML添加提升属性中。将其设置为5dp。

<TextView
    android:id="@+id/myText"
    ...
    android:elevation="5dp" />

答案 1 :(得分:0)

在API&gt; = 21上,您可以直接使用CustomViewOutlineProvider

CustomViewOutlineProvider.java

@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
public class CustomViewOutlineProvider extends ViewOutlineProvider {
    int roundCorner;

    public CustomViewOutlineProvider(int round) {
        roundCorner = round;
    }

    @Override
    public void getOutline(View view, Outline outline) {
        outline.setRoundRect(0, 0, view.getWidth(), view.getHeight(), roundCorner);
    }
}

活动

    TextView textView = (TextView) findViewById(R.id.shadow_txt);
    textView.setOutlineProvider(new CustomViewOutlineProvider(30));
    textView.setClipToOutline(true);

对于Prelollipop设备(API&lt; 21)

    <TextView
        android:background="@drawable/btn_with_shadow"
        android:gravity="center"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Font Style"
        android:textColor="@color/white"
        android:paddingRight="24dp"
        android:paddingLeft="24dp"
        android:paddingTop="12dp"
        android:paddingBottom="12dp"
        />

btn_with_shadow.xml

<layer-list
    xmlns:android="http://schemas.android.com/apk/res/android">

    <item android:drawable="@drawable/btn_shadow"/>
    <item
        android:drawable="@drawable/bg_button"
        android:bottom="4px"
        android:top="3px"
        android:right="4px"
        android:left="3px"/>

</layer-list>

btn_shadow.xml

<shape android:shape="rectangle"
    xmlns:android="http://schemas.android.com/apk/res/android">

    <solid android:color="@color/alpha_15"/>
    <corners android:radius="20dip"/>

</shape>

bg_button.xml

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">

    <solid android:color="@color/colorPrimary"/>
    <corners android:radius="20dp" />

</shape>

colors.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="colorPrimary">#3F51B5</color>
    <color name="colorPrimaryDark">#303F9F</color>

    <color name="alpha_15">#26000000</color>
</resources>

结果 -

Button with Shadow