简体   繁体   中英

How can I create a shadow in a TextView?

I have one requirement to create shadow in TextView?

How can I achieve it? attached screensort.

在此处输入图片说明

If have any idea then let me know.

Thanks!!! in advance.

In your XML add elevation property. Set it to 5dp.

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

On API>=21 you can directly use 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);
    }
}

Activity

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

For Prelollipop Devices(API<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>

Result -

带阴影的按钮

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM