Thursday 29 May 2014

Custom textview in android


Custom textview in android :          

In android sometime we have to set the external effect to the textview. In 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 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:

Dont forget to add "android-support-v7-appcompat" in this project when import.

Screenshot:


No comments: