Learn Android Development For Beginners

Text Controls

Text controls are most common controls use to build user interface. The Android provides following text controls

Text View

The text view control is the most common control to design the User Interface of the application. It displays the static text on the UI and expose some properties that helps to makes professional UI.

If you design UI using designer, the control palette shows four default text view controls Plain Text, Large Text, Medium Text and small Text.

Let’s first start with these four different types of the Text View control. In the Layout XML file all Text View controls use <TextView> element and the only difference is the “android:textAppearance” attribute. It is different for each type. Drop each type of control on layout using designer and See the XML of layout.

    
 <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="New Text"
        android:id="@+id/txtPlainText" />

 <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:text="Large Text"
        android:id="@+id/textView2" />

 <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:text="Medium Text" />

 <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceSmall"
        android:text="Small Text" />

    

It Use android core style attributes to create layouts which look similar to standard android layouts.

 android:textAppearance="?android:attr/textAppearanceLarge"
 android:textAppearance="?android:attr/textAppearanceSmall"

Set Text

In xml layout use android:text to property to set the content of the TextView control.

 android:text="Large Text"
    

Android also expose a "setText()" method to set content of the TextView through code.

 TextView txtPlainText = (TextView)findViewById(R.id.txtPlainText);

 txtPlainText.setText("Plain text set from code.");
    

Find the control by id in the code and set its text. Execute the program and the output of the program will look like image below.

In android <textview> control has very interesting properties that makes it handy. If TextView has Web Url or Email address in its content use autoLink property to web|email, the control finds and highlight any email and web URL in the content. Android TextView also has text color, background and font size etc. properties to design application and it also provide a way to format content using HTML tags.

AS other programming languages Android provides a provision to set the controls properties using XML and code. In the next coming examples we will learn how to use the different properties of text view for designing layout.

Set background color

android:background property is use to set the background of the TextView. The possible value can be a color, any resource etc. The android:background="#a6cbff" sets the light blue color as a background color. The format of the color code is “#AARRGGBB” where AA the Alpha of the color that sets the opacity. The alpha value “00” means that color is fully transparent and “FF” that it’s not transparent at all, so you could skip this information.

<TextView
        android:text="Set Properties in XML"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:padding="8dp"
        android:layout_marginBottom="10dp"
        android:background="#a6cbff"
        android:textStyle="bold" />
    

Set the layout_width property to fill_parent or match_parent to stretch the textview horizontally. Apply some padding and margin to TextView.

All these properties can be set using code. Use “setBackgroundColor()” method to set the background color of the control. Set the padding using “setPadding()” method and margins using “setMargins()” mehod of the layout. See the code below to set properties using code.

 protected void SetTitleTextView()
 {
       
     TextView tvTitle = (TextView)findViewById(R.id.tvTitle);

     tvTitle.setBackgroundColor(0xFFA6CBFF);

     int padding8Dp = GetDpValue(8);
     tvTitle.setPadding(padding8Dp, padding8Dp, padding8Dp, padding8Dp);
     tvTitle.setTypeface(null, Typeface.BOLD);

     LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.MATCH_PARENT,
                LinearLayout.LayoutParams.WRAP_CONTENT);

        params.setMargins(0, 50, 0,10);
        tvTitle.setLayoutParams(params);

 }

Set Text Style (Bold and Italic)

The textStyle property is use to set the text Bold and Italic. android:textStyle="bold" makes text bold and android:textStyle="italic" makes text italic. Use "|" separator to make bold and italic e.g. android:textStyle="bold|italic".

 android:textStyle="bold"
 android:textStyle="italic"
 android:textStyle="bold|italic"
    

setTypeface() method is use for making text bold and italic using code.

 element.setTypeface(null, Typeface.BOLD | Typeface.ITALIC);

Set Text Color, Size and Face

android:textColor property is use to set the color of the text. android:textSize is use for setting font size and android:typeface is use for setting font face.

 <TextView
        android:text="Text & Font Style"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textColor="#fff200"
        android:textSize="36dp"
        android:typeface="serif"
        android:textStyle="bold|italic"
        android:paddingStart="10dp" />

android:textColor property is use to set the color of the text. android:textSize is use for setting font size and android:typeface is use for setting font face. There are also methods available to do setting using code.

 protected void SetFontTextView()
 {
    TextView tvTitle = (TextView)findViewById(R.id.tvFont);

    tvTitle.setTextColor(0xFFfff200);
    tvTitle.setTextSize(36);
    tvTitle.setPadding(GetDpValue(10), 0, 0, 0);

    tvTitle.setTypeface(Typeface.SERIF, Typeface.BOLD | Typeface.ITALIC);
 }

setTextColor() method sets the foreground color of the text view, setTextSize() method sets the size of the font and setTypeface() method is use for setting font face and style.

Auto Link and Link Color

If autoLink property is set, it finds the email, phone or web URL in the content as per setting and highlight them and make them clickable. The possible value of the autoLink properties can be “none, web, email, phone, map and all”.

 android:autoLink="email"
 android:autoLink="web"
 android:autoLink="email|web"
 android:autoLink="all"
           

android:autoLink="email" finds email address in the content and highlight it. android:autoLink="web" finds web URL in the content and highlight it. Use “|” separator more than one setting is required. android:autoLink="email|web" highlights email and web URL in the contents. android:autoLink="all" highlight all the linkable contents.

For example set the content in the XML layout that contains the email address, Web URL and phone in its content. Set the autoLink property to all.

 <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:text="Please visit my website, http://www.brainysolutions.org/ 
                      or email me at admin@brainysolutions.org. or call at 1 234-567-8901"
        android:autoLink="all" />

Run the application, the email address, web URL and phone is highlighted and on the click of them Android opens appropriate application for it e.g. on click of Web URL it opens the web Browser.

TextView control has “textColorLink” property to change the color of highlighted link.

 android:textColorLink="#ff050a"

Run the application and now you can see the highlighted link color is red.

There is also a addLinks() method of the Linkify class to find and add links to the content of the TextView from code.

 protected void SetLinkText()
 {
    TextView tv =(TextView)this.findViewById(R.id.tvLinks);
    Linkify.addLinks(tv, Linkify.ALL);

    tv.setLinkTextColor(0xFFff050a);
 }

addLink() method can also take more than one settings by separating | sign.

  Linkify.addLinks(tv, Linkify.WEB_URLS);

  Linkify.addLinks(tv, Linkify.WEB_URLS|Linkify.EMAIL_ADDRESSES);

Max Length and Lines

You can also limit the contents to be shown using “maxLength” property. E.g. add the text view and set its maxLength property “20”.

<TextView
        android:text="Hello Hi i am going to write Second line..."
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"

        android:maxLength="20" />
    

Run the application and this text view displays only first 20 character.

    Hello Hi i am going

maxLines limit the content to max line and minLines reserves the minimum lines space for the text view

 android:maxLines="2"
 android:minLines="2"

Display HTML in Text View

Android TextView can also displays HTML in its contents. See the code snippet below that shows the HTML text in the TextView

 protected void SetHtmlColor()
 {
    TextView tv =(TextView)this.findViewById(R.id.tvHtmlColor);
    tv.setText(Html.fromHtml("This is <b>Bold</b> text.<br/> This is <i>Italic</i>. RGB colors are  " +
                "<font color='#FF0000'>Red</font>, " +
                "<font color='#00FF00'>Green</font>, " +
                "<font color='#0000FF'>Blue</font>"));
 }



EditText

Edit text is the subclass of the TextView control and allows text editing. In the control Palette Android designer shows different types of Edit Text controls e.g. Plain Text, Password, E-mail etc.

Add the some EditText Control in the layout file. The <EditText> xml element is use for Edit text. If you put some Edit Text controls in the UI the only difference is the “inputType” property.

<EditText
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_margin="4dp" />

<EditText
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:inputType="textPersonName"
                android:text="Name"
                android:layout_margin="4dp" />

<EditText
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:inputType="textPassword"
                android:layout_margin="4dp" />

 <EditText
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:inputType="textEmailAddress"
                android:layout_margin="4dp" />

EditText has different input types such as email, Number, date etc. These types specify which type of characters is allowed for this field. Android automatically change keyboard as per Edit Text input type. See the keyboard image below for different input types.


(Text)

(Email)

(Number)

(Phone)

You can see the Keyboard behavior of the application for different input types. e.g @ sign with normal keyboard for email input type, basic Number keypad for input type number etc.

User can select more than one input types by separating with | sign. From property palette in design view user can also select multiple input types.

For example if EditText has “textPostalAddress”, “textCapWords” and “textNoSuggestions” as inputType. On start of the every word the keyboard will automatically shift to Upper case and suggestions will be also disabled.

<EditText
          android:layout_width="match_parent"
          android:layout_height="wrap_content"
          android:hint="Enter you address here"
          android:inputType="textPostalAddress|textCapWords|textNoSuggestions" />

Get and Set Text

Same as TextView, EditText has “Text” property to get or set text. In layout file you can set text using android:text property.

 <EditText
          android:id="@+id/editText"
          android:layout_width="match_parent"
          android:layout_height="wrap_content"
          android:text="Name" />
    

From code file call the setText() method of the EditText to set content

 EditText et =(EditText)this.findViewById(R.id.editText);
 et.setText("Set text From Code");

Call getText() method to get the text from edit text.

 EditText et =(EditText)findViewById(R.id.editText);
 String message = et.getText().toString(); 

Background and Text Color

EditText is the subclass of the TextView and its most of the properties are same as TextView e.g. background color, text color etc. properties are same as TextView

 <EditText
          android:layout_width="match_parent"
          android:layout_height="wrap_content"
          android:inputType="textPersonName"
          android:text="Name"
          android:layout_margin="4dp"
          android:background="#ff2c39"
          android:textColor="#ffffff" />

Hint

You can show hint text when EditText is empty by setting android:hint property. The hint text disappears when user enter text in the edit text.

 <EditText
         android:layout_width="match_parent"
         android:layout_height="wrap_content"
         android:layout_margin="4dp"
         android:hint="Enter Text Here" />

Styling using HTML

You can also style content using HTML tag in EditText. Add the string resource in the strings.xml file and assign it to the text property of the EditText. E.g. add the following entry in strings.xml.

 <string name="styledText"><i>Static</i>  style in an <b>EditText</b>.</string>

In the layout file add the EditText and set text property as "@string/styledText".

 <EditText
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_margin="4dp"
                android:text="@string/styledText" />

A style can be set from the code file. setSpan() method of the Spannable class is use for applying style . For applying style from code, add the EditText in the layout file.

 <EditText
                android:layout_width="match_parent"
                android:layout_height="100dp"
                android:inputType="textMultiLine"
                android:layout_margin="4dp"
                android:id="@+id/etMultiText" />

Get the text of the edit text using getText() method and assign it to the instance of the Spannable class. getText() method returns the instance of Editable class which is the derived from Spannable and it can be directly assigned to Spannable object. Call the setSpan() method of the Spannable class to set RED background color of first 7 characters and make them Bold & Italic.

 protected void SetStyle()
 {
        EditText et =(EditText)this.findViewById(R.id.etMultiText);
        et.setText("Styling the content of an editText dynamically");
        Spannable spn = et.getText();

        spn.setSpan(new BackgroundColorSpan(Color.RED), 0, 7,
                Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        
        spn.setSpan(new StyleSpan(android.graphics.Typeface.BOLD_ITALIC)
                , 0, 7, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

 }



AutoCompleteTextView

AutoCompleteTextView is a TextView with auto complete functionality. It shows the suggestions as user type text in TextView. For autocomplete suggestions user needs to provide a list of suggestion from code. The example below shows how to use the AutoCompleteTextView control. Add the AutoCompleteTextView in layout file.

 <AutoCompleteTextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text=""
        android:id="@+id/autoCompleteTextView" />

For binding the suggestion list with AutoCompleteTextView associate the suggested list using setAdapter() method.

 AutoCompleteTextView autoCompleteTextView = (AutoCompleteTextView)this.findViewById(R.id.autoCompleteTextView);

 String[] countryList = new String[]{"Afghanistan", "Albania", "Algeria", "Andorra", "Angola",
                "Antigua & Deps", "Argentina", "Armenia", "Australia", "Austria", "Azerbaijan",
                "Bahamas", "Bahrain", "Bangladesh", "Barbados", "Belarus", "Belgium", "Belize",
                "Benin", "Bhutan", "Bolivia", "Bosnia Herzegovina", "Botswana", "Brazil", "Brunei",
                "Bulgaria", "Burkina", "Burundi", "Cambodia", "Cameroon", "Canada", "Cape Verde",
                "Central African Rep", "Chad", "Chile", "China", "Colombia", "Comoros", "Congo",
                "Congo {Democratic Rep}", "Costa Rica", "Croatia", "Cuba", "Cyprus", "Czech Republic",
                "Denmark", "Djibouti", "Dominica", "Dominican Republic", "East Timor", "Ecuador", "Egypt"};

 ArrayAdapter<string> autoList = new ArrayAdapter<String>(this,
                android.R.layout.simple_dropdown_item_1line, countryList);

 autoCompleteTextView.setAdapter(autoList);
 
 

The adapter bind the collection to the control, don’t worry about the adapter at this stage we will learn about it later.



MultiAutoCompleteTextView

The AutoCompleteTextView offers suggestions only for the entire text in the TextView. It does not give suggestion for each word. MultiAutoCompleteTextView gives suggestions for each word in the sentence.The use of AutoCompleteTextView and MultiAutoCompleteTextView is almost same. The only difference is in MultiAutoCompleteTextView we have to tell the control where to start suggesting again. See the image below that gives suggestion after every comma (,).

Add the MultiAutoCompleteTextView in the Layout file and set its id.

<MultiAutoCompleteTextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text=""
        android:id="@+id/multiAutoCompleteTextView"/>

Set the countries name list using setAdapter() method. The MultiAutoCompleteTextView requires a Tokenizer that can parse a sentence and tell it whether to start suggesting again. See the code below.

 MultiAutoCompleteTextView autoCompleteTextView = (MultiAutoCompleteTextView) this.findViewById(R.id.multiAutoCompleteTextView);

 String[] countryList = GetCountries();

 ArrayAdapter<String> autoList2 = new ArrayAdapter<String>(this,
                android.R.layout.simple_dropdown_item_1line, countryList);

 autoCompleteTextView.setAdapter(autoList2);

 autoCompleteTextView.setTokenizer(new MultiAutoCompleteTextView.CommaTokenizer());

Run the application and start typing in the EditText, the suggestion will be displayed after every comma (,) typed in the sentence because of CommaTokenizer.

Download Source Code

You can get the source code. Download Source Code

;