Android TextView


Android TextView is a User interface widget that displays basic texts.

In almost every Graphical User Interface toolkit out there, a component or control for displaying text is there. Be it the Label in Windows Forms or the JLabel in Swing.

This is because we mostly communicate via texts and these texts have to be rendered. Well the textview renders them in Android.

TextViews and labels are normally considered basic and are easy to work with.

In android textviews are actually editable though by default this is disabled. Instead it's subclass the EditText on the other hand allows for editing.

TextView as a class resides in the android.widget package.

package android.widget;

TextView derives from android.view.View class and implements import android.view.ViewTreeObserver.OnPreDrawListener.

public class TextView extends View implements OnPreDrawListener {}

TextViews can be created either programmatically or via inflation of XML. Here are the constructors to create a TextView object programmatically.

No. Constructor
1. public TextView(Context context)
2. public TextView(Context context, AttributeSet attrs)
3. public TextView(Context context, AttributeSet attrs, int defStyleAttr)
4. public TextView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes)

Let's look at various TextView examples:

Creating TextView From XML Definition

Most of the time we define textviews via xml and inflate them in our activity. Here's a typical definition of android textview;

<TextView
    android:id="@+id/greetingsTxt"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Hello World!"
/>
  • First we specify a unique id for the textview usingandroid:id="" attribute that will be used to reference the textview from C# code.
  • We then define the layout width(android:layout_width="") and height(android:layout_height="") of the textview.
  • Next we specify the text via the android:text="" attribute.

We then come to our MainActivity's OnCreate() method. OnCreate() method is a lifecycle callback that gets called when the activity in android has been created.

Normally we make view initializations here since the activity has been created.

But first we make sure that the following method has been invoked:

setContentView(R.layout.activity_main);
```language

The above method will inflate our activity_main.axml layout and set it as the layout of our activity. This layout has to be inflated first since it contains our TextView.

Then we come reference our TextView:

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

This will give us a textview reference which we can use to set text:

 greetingsTxt.setText("Hello World Over there");

If we run the project we get:

Xamarin TextView Example

Here's the full source code: activity_main.axml:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.tutorials.hp.textviewapp.MainActivity">

    <TextView
        android:id="@+id/greetingsTxt"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!"
        />
</RelativeLayout>

MainActivity.java

package com.tutorials.hp.textviewapp;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        TextView greetingsTxt= (TextView) findViewById(R.id.greetingsTxt);
        greetingsTxt.setText("Hello World Over there");
    }
}

Creating TextView Programmatically as the ContentView of an Activity

It's not mandatory that you set a layout as the content view of an activity.

You can use a view instead of inflating a layout. If anything the layouts do get inflated into a view object.

However this is only suitable for simple interfaces. if you need a complex interface with nested widgets, then you use the layout as it's easier to write such declaratively.

First we instantiate a TextView programmatically, passing in the Context object:

TextView greetingsTxt=new TextView(this);

Let's then set the textview's background color programmatically:

greetingsTxt.setBackgroundColor(Color.GREEN);

Then set the text:

greetingsTxt.setBackgroundColor(Color.GREEN);

And finally set the content view:

setContentView(greetingsTxt);

Here's the full code. Note we don't need an xml layout:

package com.tutorials.hp.textviewapp;

import android.graphics.Color;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        TextView greetingsTxt=new TextView(this);
        greetingsTxt.setBackgroundColor(Color.GREEN);
        setContentView(greetingsTxt);
    }
}

Here's what we get: Android TextView Example

Here's another example of building a textview programmatically with several attributes being set:

private TextView buildTextView(Context context, CharSequence text) {
    TextView textView = new TextView(context);
    LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(0, ViewGroup.LayoutParams.MATCH_PARENT, 1);
    textView.setLayoutParams(params);
    textView.setTextColor(mTextColor);
    textView.setText(text);
    textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, mTextSize);
    textView.setMaxLines(3);
    textView.setEllipsize(TextUtils.TruncateAt.END);
    textView.setGravity(Gravity.CENTER);
    textView.setPadding(mPaddingHorizontal, mPaddingVertical, mPaddingHorizontal, mPaddingVertical);
    return textView;
}

Hiding a TextView

What about if you want to hide a textview. Well it's a view so we can simply set it's visibility to View.GONE:

public void hideTextView()
{
    TextView positive = (TextView) findViewById(R.id.action_positive);
    positive.setVisibility(View.GONE);
    TextView negative = (TextView) findViewById(R.id.action_negative);
    negative.setVisibility(View.GONE);
}

Using TextView in a Fragment

Well just override the onCreateView() method of your Fragment, then first make sure the Fragment layout is inflated into a View object.

Then find the textview from that inflated view:

  TextView tv = (TextView) view.findViewById(R.id.text);

Then of course you can set it's text property as you wish:

@Nullable @Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container,
    @Nullable Bundle savedInstanceState) {

  View view = inflater.inflate(R.layout.fragment_child, container, false);
  TextView tv = (TextView) view.findViewById(R.id.text);
  tv.setText(toString());

  return view;
}

Common TextView Methods and examples

1. setText()

To set text to a textview you simply use the setText() method.

TextView nameTxt = (TextView) findViewById(R.id.nameTxt);
nameTxt.setText(msg);

What about if you want to set text that has been sent from another activity:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_counter);

    TextView courseTxt = (TextView) findViewById(R.id.textView3);
    courseTxt.setText(getIntent().getStringExtra("course_id"));
    courseTxt.setTextColor(Color.WHITE);
}
2. setTextColor()

Let's say we have the color in defined in the colors.xml resource, so we load the color from there using getResources().getColor() invokation.

nameTxt.setTextColor(mContext.getResources().getColor(R.color.text_black));

You can also set color literal in hexadecimal notation(using the characters '0x' followed by the hexadecimal number) like this;

nameTxt.setTextColor(0xFF000000);

This is the Opaque black color we've used.

However we can also set the color from the android.Graphics.Color class as follows:

nameTxt.setTextColor(Color.BLACK);
nameTxt.setTextColor(Color.WHITE);
3. setBackgroundColor()

Well we are also capable of setting the background color of a textview:

nameTxt.setBackgroundColor(getResources().getColor(R.color.color_yellow_fcf3cd));
5. setGravity()
nameTxt.setGravity(Gravity.CENTER);
6. setTextSize()
nameTxt.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 13);
7. setSingleLine()
nameTxt.setSingleLine();
8. setTypeface()
Typeface font = FontManager.getInstance().getFont(FontManager.Font.ROBOTO_LIGHT);
nameTxt.setTypeface(font);
9. setId()
nameTxt.setId((int) getItemId(position));
10. setLayoutParams()
nameTxt.setLayoutParams(new RelativeLayout.LayoutParams(-1, -1));
11. How to add and Cancel Strike Through to TextView

These two methods show us how to add or cancel a strike through in a textview widget.

You just pass that textView as a parameter and we invoke the setPaintFlags() with the appropriate parameters. We utilize the Paint class, which normally holds the style and color information about how to draw geometries, text and bitmaps.

    // Set the strikethrough 
    public static void addStrikeThrough(TextView textView) {
        textView.setPaintFlags(textView.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);
    } 

    // Cancel the strikethrough 
    public static void removeStrikeThrough(TextView textView) {
        textView.setPaintFlags(textView.getPaintFlags() & (~Paint.STRIKE_THRU_TEXT_FLAG));
    } 
11. postDelayed()
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    place = (TextView) findViewById(R.id.tv_placeholder);
    textView = (TextView) findViewById(R.id.tv_info);
    textView.postDelayed(new Runnable() {
        @Override
        public void run() {
            place.setVisibility(View.GONE);
            if (EmulatorDetector.getDefault().isEmulator()) {
                textView.setText("This device is emulator\n" + EmulatorDetector.getDefault().getEmulatorName());
            } else {
                textView.setText("This device is not emulator\n");
            }
        }
    }, 1000L);
}
12. How to create a Gradient TextView
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.LinearGradient;
import android.graphics.Paint;
import android.graphics.Shader;
import android.os.Build;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.widget.TextView;

public class GradientTextView extends TextView {

    public GradientTextView(Context context) {
        super(context);
    } 

    public GradientTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
    } 

    public GradientTextView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    } 

    @Override 
    protected void onDraw(Canvas canvas) {
        CharSequence text = getText();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
            if(!TextUtils.isEmpty(text)&&text.length()<getMaxEms()){
                super.onDraw(canvas);
                return; 
            } 
        } 
        Paint mPaint = getPaint();
        //获取字体颜色并计算渐变色 
        int textColor = getCurrentTextColor();
        int endColor = textColor & 0x00ffffff; //透明度设为0:(颜色值高8位设置为0)
        LinearGradient mLinearGradient = new LinearGradient(0, 0, getMeasuredWidth(), 0, new int[]{textColor, endColor}, new float[]{0.5f, 1f}, Shader.TileMode.REPEAT);
        mPaint.setShader(mLinearGradient);
        super.onDraw(canvas);
    } 
} 

More

Let's look at some examples.

{% set card_number = 1 %} {% for p in page.find('/android/textview').children if p != page %}
{{ card_number }} . {{ p.title }}

{% if p.summary != p.content %} {{ p.summary }} {% else %} {{ p.content }} {% endif %}
{% set card_number = card_number + 1 %} {% endfor %}

How do You Feel after reading this?

According to scientists, we humans have 8 primary innate emotions: joy, acceptance, fear, surprise, sadness, disgust, anger, and anticipation. Feel free to tell us how you feel about this article using these emotes or via the comment section. This feedback helps us gauge our progress.

Help me Grow.

I set myself some growth ambitions I desire to achieve by this year's end regarding this website and my youtube channel. Am halfway. Help me reach them by:




Recommendations


What do You Think


Previous Post Next Post