Friday, May 22, 2015

How to set TextView text shadow programmatically in Android

activity_main.xml

<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/rl"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="16dp"
    tools:context=".MainActivity"
    android:background="@android:color/white"
    >
    <TextView
        android:id="@+id/tv"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Sample TextView..."
        android:padding="25dp"
        android:textSize="30dp"
        android:textStyle="bold"
        android:textColor="#ffff0045"
        />
    <Button
        android:id="@+id/btn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Set Text Shadow"
        android:layout_below="@id/tv"
        />
</RelativeLayout>
MainActivity.java

package com.cfsuman.me.androidcodesnippets;

import android.graphics.Color;
import android.os.Bundle;
import android.app.Activity;
import android.view.View;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.TextView;

public class MainActivity extends Activity{

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // Get the widgets reference from XML layout
        RelativeLayout rl = (RelativeLayout) findViewById(R.id.rl);
        final TextView tv = (TextView) findViewById(R.id.tv);
        Button btn = (Button) findViewById(R.id.btn);

        // Set a click listener for Button widget
        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                /*
                    public void setShadowLayer (float radius, float dx, float dy, int color)

                    Gives the text a shadow of the specified blur radius and
                    color, the specified distance from its drawn position.

                    shadowColor
                        Place a blurred shadow of text underneath the text,
                        drawn with the specified color.
                    shadowDx
                        Horizontal offset of the text shadow.
                    shadowDy
                        Vertical offset of the text shadow.
                    shadowRadius
                        Blur radius of the text shadow.
                 */

                // Set TextView Text shadow
                tv.setShadowLayer(
                        1.5f, // radius
                        5.0f, // dx
                        5.0f, // dy
                        Color.parseColor("#FF3D803D") // shadow color
                );
            }
        });
    }
}
More android examples