Custom textview in android

Custom Textview in android     

In android sometime we have to set the external effect to the Textview. By default, Textview you cant set more effects. For that, you have to create custom Textview.Here I have written simple steps to create custom Textview in android.

Steps:
Create attrs.xml in values folder and set the attributes for the Textview.
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="testTex">

<attr name="testName" format="string"></attr>

</declare-styleable>

</resources>

Set the custom attributes to the Textview in activity_main.xml.

<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res/com.example.extendstextview"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">

<com.example.extendstextview.Textview

android:id="@+id/textvv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
app:testName="sample
testview" >
</com.example.extendstextview.Textview>
</RelativeLayout>

Create a new class and extends TextView.
Get the attributes from the attrs.xml and store it to the TypeArray.

TypedArray typedArray=context.getTheme().obtainStyledAttributes(attrs,R.styleable.testTex,0, 0);
     try{
           text=typedArray.getString(R.styleable.testTex_testName);
         }
        finally{
             typedArray.recycle();
         }

Finally imlement onDraw method,and set textview color,size and text.

setText(text);      
setTextSize(30);setShadowLayer(4, 2, 2, Color.rgb(250, 00, 250));

Note:

Don’t forget to add “android-support-v7-appcompat” in this project when import.

Screenshot

Custom Textview in android 
Download

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to Top