Sunday 1 January 2012

Underline TextView in Android

Here we can see how to underline a TextView programmatic way.  
In Android using UnderlineSpan to draw an underline for the text on TextView.
 
Through the SpannableString we can underline the text,
it can be static or dynamic text no problem,  
first we have to set the string to the SpannableString and then
we need to setSpan, and then we need to set that variable to the TextView.
 
Example:
 UI Layout (activity_underline_text.xml)
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <TextView
        android:id="@+id/underlinetxt"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text=""
        android:textSize="25px" />


</LinearLayout>

Android Activity class(UnderlineText.Class)
package com.androidsurya.underlinetext;

import android.app.Activity;
import android.os.Bundle;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.style.UnderlineSpan;
import android.view.Menu;
import android.widget.TextView;

public class UnderlineText extends Activity {

 @Override
   protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_underline_text);
SpannableString str = new SpannableString("This is Underline text");
str.setSpan(new UnderlineSpan(), 0, str.length(),
Spanned.SPAN_PARAGRAPH);
TextView txtView = (TextView) findViewById(R.id.underlinetxt);
txtView.setText(str);
  
 }

 @Override
 public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_underline_text, menu);
return true;
 }

}

Register Activity in Android Manifestfile

<activity
            android:name="com.androidsurya.underlinetext.UnderlineText"
            android:label="@string/app_name" >

Output Screenshot:
 

No comments:

Post a Comment

Android SQLite Database Viewer or Debuging with Stetho

Every Android Developer uses SQLite Database to store data into the Android Application data. But to view the data in SQLite have a lot of...