Tuesday, January 3, 2012

Android Views – TextView



Text view is most commonly used control across applications. It is used to display texts. In android, not only text, you can also display html text in text view. Texts in Text views can be modified and formatted easily.  

There are two ways how you can add text view into a layout,

1.       Through designer, by drag and drop onto layout or just edit xml file and type it manually.
2.       Add text view on the fly through code.

What all you can do with text view? Well, here is the list of few important things.

1.       Change font type – use built-in font types (limited) or refer to external font file. To use external font file, add font file (.ttf) into assets folder and import into text view using TypeFace object.            
      ex:  Typeface newtypeface = Typeface.createFromAsset(getAssets(), "Amazone BT.ttf");

2.       Change font style – bold, normal, italic (anyone at a time, multiple style only through text as html).

3.       Change font size – using a float value and unit to use.When no unit is specified, android defaults to pixels. Preferred units are dp/dip and sp. (pixels are not preferred in android as it varies across devices).

4.       Change text color – you can change text color and text background color. Text color attribute accepts only hexadecimal values when assigned in layout file. If you are adding color from code, it’s better to use Color class of android or manually create your color using hexadecimal values and add it. Text background accepts both color values and images.

5.       Text appearances – create your own style and refer it or use android built-in text appearances.

6.       Modify text dynamically through code.

7.       Bind events and act accordingly. Ex: click event, touch event, focus event etc...

Text appearance defines how your text should look to user. There are few ways how you can modify your text.

1.       Styled and formatted in layout file.
2.       If needs are simple, android’s built-in styles can be used.
3.       If you want to make some really attractive formatting and re-use it, then define the style by yourself in style.xml file and refer it either in layout file or through code using resource id. Ex: R.style.yourstyle 

Here is an example of how you can use text view in android.

TextViewDemoActivity.java

package com.coffeewithtechie.textviewdemo;

import android.app.Activity;
import android.graphics.Color;
import android.graphics.Typeface;
import android.os.Bundle;
import android.text.Html;
import android.util.TypedValue;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.LinearLayout;
import android.widget.TextView;

public class TextViewDemoActivity extends Activity {

                TextView tv4;
                TextView tv5;
                TextView tv6;
               
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
       
         tv4 = (TextView)findViewById(R.id.textView4);       
        Typeface newtypeface = Typeface.createFromAsset(getAssets(), "Amazone BT.ttf"); // font file referred from assests folder
         tv4 .setTypeface(newtypeface);
       
         tv5 = (TextView)findViewById(R.id.textView5);
         tv5 .setText(Html.fromHtml("
this is html string
")); // html text, only basic html tags works, styles doesn't work
       
         tv6 = (TextView)findViewById(R.id.textView6);
//        tv6.setOnClickListener(new OnClickListener() {
//                                           
//                                            @Override
//                                            public void onClick(View v) {
//                                                            // TODO Auto-generated method stub
//                                                            String text = tv6.getText().toString(); // get textview text value
//                                                            text = "you clicked me!";
//                                                            tv6.setText(text); // modify text dynamically
//                                            }
//                            });
       
         tv6.setOnTouchListener(new OnTouchListener() {
                                               
                                                @Override
                                                public boolean onTouch(View v, MotionEvent event) {                                                                
                                                                String text =  tv6.getText().toString(); // get textview text value
                                                                text = "you touched me! at x:"+ event.getX()+" y:"+ event.getY()+" positions";
                                                                 tv6.setText(text); // modify text dynamically
                                                                return true;
                                                }
                                });
       
        //dynamic textview
        TextView tvDynamic = new TextView(this);
        tvDynamic.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
        tvDynamic.setText("Dynamic text view, styled from code");
        tvDynamic.setTextColor(Color.MAGENTA);      
        tvDynamic.setTextSize(TypedValue.COMPLEX_UNIT_MM, 5f); // font size in millimeter
       
        LinearLayout layoutparent = (LinearLayout)findViewById(R.id.layoutparent);
        layoutparent.addView(tvDynamic); //adding newly created text view to layout
       
        tvDynamic.setTextAppearance(this, R.style.CustomTextViewStyle);
       
    }
}

Main.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:id="@+id/layoutparent"
    android:orientation="vertical" >

    <TextView android:background="#aaaaaa"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/hello"  />

    <TextView
        android:background="@drawable/backgroun"
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="styled in xml"
        android:textColor="#887722"
        android:textSize="30dp"  
        android:textStyle="italic"
        android:typeface="serif"  
         />

    <TextView
        android:id="@+id/textView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Styled with built in android styles"
        android:textAppearance="@android:style/TextAppearance.Widget.TextView.PopupMenu" />
       
       <TextView
        android:id="@+id/textView3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Styled with custom styles"
        android:textAppearance="@style/CustomTextViewStyle" />
           
       <TextView
        android:id="@+id/textView4"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Text with font type from external source"
        android:textSize="25dp"
        /> 

       <TextView
        android:id="@+id/textView5"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"       
        /> 
       <TextView
        android:id="@+id/textView6"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"     
        android:text="Touch me!"        
        />
</LinearLayout>

Values/styles.xml

create a style.xml file under values folder and the below code

xml version="1.0" encoding="utf-8"?>
<resources>
<style name="CustomTextViewStyle">
    <item name="android:textColor">#ff0000<item>
    <item name="android:textSize">26sp<item>  
    <item name="android:textStyle">bold<item>        
style>   
resources>

This is how it looks when executed.
output - before touch event

Text modifies dynamically after touching “Touch me!” text view.

output - after executing touch event 

No comments:

Post a Comment