Detailed explanation of Android's TextView (text box)

Introduction to this section:

After learning the six major layouts in Android, starting from this section we will explain the UI controls in Android one by one. The UI controls brought to you in this section are: TextView (text box), a control used to display text. In addition Let me make it clear that I am not translating API documents, and I will not deduct attributes one by one. I only learn the commonly used and useful ones in actual development. If you encounter unfamiliar attributes, you can query the corresponding API! Of course, at the beginning of each section, a link to the API document corresponding to this section will be posted: TextView API  Okay, before starting this section, we need to introduce the following units:

dp (dip):  device independent pixels. Different devices have different display effects, which are related to the device hardware. Generally, we recommend using this to support WVGA, HVGA and QVGA, which does not rely on pixels. px: pixels . The display effects of different devices are the same. Generally, HVGA represents 320x480 pixels, which is more commonly used. pt: point is a standard unit of length, 1pt = 1/72 inch, used in the printing industry, very simple and easy to use;  sp: scaled pixels (enlarged pixels) . Mainly used for font display best for textsize.

1. Detailed explanation of basic attributes:

Through the following simple interface, we will understand a few of the most basic attributes:

Layout code:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity"
    android:gravity="center"
    android:background="#8fffad">

    <TextView
        android:id="@+id/txtOne"
        android:layout_width="200dp"
        android:layout_height="200dp"
        android:gravity="center"
        android:text="TextView(display box)"
        android:textColor="#EA5246"
        android:textStyle="bold|italic"
        android:background="#000000"
        android:textSize="18sp" />

</RelativeLayout>

The above TextView has the following properties:

  • id: Set a component id for TextView. Based on the id, we can obtain the object through the findViewById() method in the Java code, and then set the relevant properties, or when using RelativeLayout, the reference component also uses the id!
  • layout_width: the width of the component, usually written as: **wrap_content** or **match_parent(fill_parent)**, the former is the size of the control as the content displayed by the control, and the latter will fill the parent container where the control is located; of course It can be set to a specific size. For example, for display effect, I set it to 200dp.
  • layout_height: the height of the component, the content is the same as above.
  • Gravity: Set the alignment direction of the content in the control, text in TextView, pictures in ImageView, etc.
  • text: Set the displayed text content. Generally, we write the string into the string.xml file, and then obtain the corresponding string content through @String/xxx. For convenience, I will write it directly into "". It is not recommended. Write like this! ! !
  • textColor: Set the font color, the same as above, referenced through the colors.xml resource, don’t write it directly!
  • textStyle: Set the font style, three optional values: **normal** (no effect), **bold** (bold), **italic** (italic)
  • textSize: font size, the unit is usually sp!
  • background: The background color of the control, which can be understood as the color that fills the entire control, and can be a picture!

2. Practical development examples

2.1 TextView with shadow

Several attributes involved:

  • android:shadowColor: Set the shadow color, which needs to be used together with shadowRadius!
  • android:shadowRadius: Set the blur level of the shadow. Set it to 0.1 to change the font color. It is recommended to use 3.0
  • android:shadowDx: Set the offset of the shadow in the horizontal direction, which is the abscissa position where the horizontal shadow starts.
  • android:shadowDy: Set the offset of the shadow in the vertical direction, which is the vertical coordinate position where the shadow starts in the vertical direction.

Rendering:

Implementation code:

<TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:shadowColor="#F9F900"
        android:shadowDx="10.0"
        android:shadowDy="10.0"
        android:shadowRadius="3.0"
        android:text="TextView with shadow"
        android:textColor="#4A4AFF"
        android:textSize="30sp" />

2.2 TextView with border:

If you want to set a border background for TextView, a normal rectangular border or a rounded border! The following may help you! In addition, TextView is the parent class of many other controls, such as Button, and you can also set such a border! The implementation principle is very simple, just write a ShapeDrawable resource file by yourself! Then TextView sets blackgroung as this drawable resource!

Let’s briefly talk about several nodes and attributes of the shapeDrawable resource file:

  • < solid  android:color = "xxx"> This is to set the background color
  • < stroke  android:width = "xdp" android:color="xxx"> This is to set the thickness and color of the border
  • < padding  androidLbottom = "xdp"...> This is to set the margin
  • < corners  android:topLeftRadius="10px"...> This is to set rounded corners
  • <gradient> This is to set the gradient color. The optional attributes are:  startColor : starting color  endColor : ending color  centerColor : middle color  angle : direction angle, when equal to 0, from left to right, and then turn counterclockwise, when angle = from bottom to top at 90 degrees  type : Set the type of gradient

Realization renderings:

Code:

Step 1: Write the Drawable of the rectangular border:

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" >

    <!--Set a black border-->
    <stroke android:width="2px" android:color="#000000"/>
    <!-- Gradient-->
    <gradient
        android:angle="270"
        android:endColor="#C0C0C0"
        android:startColor="#FCD209" />
    <!--Set the margins to make the space larger-->
    <padding
        android:left="5dp"
        android:top="5dp"
        android:right="5dp"
        android:bottom="5dp"/>

</shape> 

Step 2: Write a Drawable with rounded rectangular border:

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">

    <!--Set transparent background color-->
    <solid android:color="#87CEEB" />

    <!--Set a black border-->
    <stroke
        android:width="2px"
        android:color="#000000" />
    <!-- Set the radius of the four rounded corners -->
    <corners
        android:bottomLeftRadius="10px"
        android:bottomRightRadius="10px"
        android:topLeftRadius="10px"
        android:topRightRadius="10px" />
    <!--Set the margins to make the space larger-->
    <padding
        android:bottom="5dp"
        android:left="5dp"
        android:right="5dp"
        android:top="5dp" />
        
</shape>

Step 3: Set the blackground property of TextView to the two Drawables above:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#FFFFFF"
    android:gravity="center"
    android:orientation="vertical"
    tools:context=".MainActivity">

    <TextView
        android:id="@+id/txtOne"
        android:layout_width="200dp"
        android:layout_height="64dp"
        android:textSize="18sp"
        android:gravity="center"
        android:background="@drawable/txt_rectborder"
        android:text="TextView with rectangular border" />

    <TextView
        android:id="@+id/txtTwo"
        android:layout_width="200dp"
        android:layout_height="64dp"
        android:layout_marginTop="10dp"
        android:textSize="18sp"
        android:gravity="center"
        android:background="@drawable/txt_radiuborder"
        android:text="TextView with rounded borders" />


</LinearLayout>

2.3 TextView with picture (drawableXxx):

In actual development, we may encounter this requirement:

As shown in the picture, to achieve this effect, your idea may be: an ImageView for displaying pictures + a TextView for displaying text, then throw them into a LinearLayout, and then create four such small layouts in sequence, and then add another Putting it in a large LinearLayout, the effect can be achieved, but will it be a bit cumbersome? And as we said before, the fewer layout levels, the better the performance! Using drawableXxx can save the above process and directly set four TextViews to complete our needs!

Basic usage:

The core of setting pictures is actually: drawableXxx ; you can set pictures in four directions:  drawableTop (top), drawableButtom (bottom), drawableLeft (left), drawableRight (right). In addition, you can also use drawablePadding to set the distance between pictures and text. spacing!

Effect picture : (set pictures in four directions)

Implementation code:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"  
    xmlns:tools="http://schemas.android.com/tools"  
    android:layout_width="match_parent"  
    android:layout_height="match_parent"  
    tools:context="com.jay.example.test.MainActivity" >  
  
    <TextView  
        android:layout_width="wrap_content"  
        android:layout_height="wrap_content"  
        android:layout_centerInParent="true"  
        android:drawableTop="@drawable/show1"  
        android:drawableLeft="@drawable/show1"  
        android:drawableRight="@drawable/show1"  
        android:drawableBottom="@drawable/show1"  
        android:drawablePadding="10dp"  
        android:text="Zhang Quandan" />  
  
</RelativeLayout> 

Some questions:  You may find that the drawable we set like this cannot set the size by itself, and it cannot be set directly in XML; so we need to make a modification in the Java code!

The sample code is as follows:

package com.jay.example.test;  
  
import android.app.Activity;  
import android.graphics.drawable.Drawable;  
import android.os.Bundle;  
import android.widget.TextView;  
  
public class MainActivity extends Activity {  
    private TextView txtZQD;  
  
    @Override  
    protected void onCreate(Bundle savedInstanceState) {  
        super.onCreate(savedInstanceState);  
        setContentView(R.layout.activity_main);  
        txtZQD = (TextView) findViewById(R.id.txtZQD);  
        Drawable[] drawable = txtZQD.getCompoundDrawables();  
        //The following table of the array is 0~3, in order: upper left, lower right  
        drawable[1].setBounds(100, 0, 200, 200);  
        txtZQD.setCompoundDrawables(drawable[0], drawable[1], drawable[2],  
                drawable[3]);  
    }  
} 

Operation rendering:

Code analysis:

  • ①Drawable[] drawable = txtZQD.getCompoundDrawables( ); Obtain image resources in four different directions. The array elements are: upper left and lower right images.
  • ②drawable[1].setBounds(100, 0, 200, 200); Then after obtaining the resource, you can call setBounds to set the upper left and lower right coordinate points. For example, the setting here represents: The length is: 100dp from the leftmost point of the text. The width to 200dp is: extending upward 200dp from 0dp above the text!
  • ③txtZQD.setCompoundDrawables(drawable[0], drawable[1], drawable[2], drawable[3]); Reset the drawable array for TextView! If there is no picture, you can use null instead! PS: In addition, from the above we can see that we also You can call setCompoundDrawables directly in Java code to set pictures for TextView!

2.4 Use the autoLink attribute to identify the link type

When a URL, email, phone number, or map appears in the text, we can set the autoLink attribute; when we click on the corresponding part of the text, we can jump to a default APP, such as a string of numbers, click Then jump to the dialing interface!

Take a look at the renderings:

all means all are included, and the protocol header is automatically recognized~ In Java code, you can call setAutoLinkMask(Linkify.ALL); At this time, you do not need to write the protocol header, autolink will automatically recognize it, but you must also set it for this TextView: setMovementMethod(LinkMovementMethod.getInstance ()); Otherwise, clicking will have no effect!


2.5 TextView plays with HTML

As the title states, in addition to displaying ordinary text, TextView also predefines some tags similar to HTML. Through these tags, we can make TextView display different font colors, sizes, fonts, and even display pictures, links, etc.! We only need to use some tags in HTML and add support from the android.text.HTML class to complete the above functions!

PS: Of course, not all tags are supported. Commonly used ones include the following:

  • <font> : Set color and font .
  • <big> : Set the font size to be large
  • <small> : Set the font size to small
  • <i> <b> : italic bold
  • < a >: connection URL
  • <img> : picture

If you setText directly, it will have no effect. We need to call the Html.fromHtml() method to convert the string into the CharSequence interface, and then set it. If we need corresponding settings, we need to set them for TextView and call the following method: Java setMovementMethod(LinkMovementMethod.getInstance())

Well, let’s write code to try:

1) Test text and hyperlink tags

package jay.com.example.textviewdemo;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.Html;
import android.text.method.LinkMovementMethod;
import android.text.util.Linkify;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        TextView t1 = (TextView)findViewById(R.id.txtOne);
        String s1 = "<font color='blue'><b>Just search Baidu and you will know~:</b></font><br>";
        s1 += "<a href = 'http://www.baidu.com'>Baidu</a>";
        t1.setText(Html.fromHtml(s1));
        t1.setMovementMethod(LinkMovementMethod.getInstance());
    }
}

Operation rendering:

Well, the test is completed~

2) Test the src tag and insert pictures:

Take a look at the running effect diagram:

Next, let’s take a look at the implementation code. The implementation code looks a bit complicated and uses reflection (by the way, don’t forget to put an icon picture in the drawable directory!):

public class MainActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        TextView t1 = (TextView) findViewById(R.id.txtOne);
        String s1 = "Picture:<img src = 'icon'/><br>";
        t1.setText(Html.fromHtml(s1, new Html.ImageGetter() {
            @Override
            public Drawable getDrawable(String source) {
                Drawable draw = null;
                try {
                    Field field = R.drawable.class.getField(source);
                    int resourceId = Integer.parseInt(field.get(null).toString());
                    draw = getResources().getDrawable(resourceId);
                    draw.setBounds(0, 0, draw.getIntrinsicWidth(), draw.getIntrinsicHeight());
                } catch (Exception e) {
                    e.printStackTrace();
                }
                return draw;
            }
        }, null));
    }
}

Hehe, you can also try it yourself, such as adding a hyperlink to the picture and clicking on the picture to jump like this~

2.6 SpannableString&SpannableStringBuilder customized text

In addition to the above HTML that can customize the style of our TextView, it can also be done using SpannableString and SpannableStringBuilder. The difference between the two is: the former is for immutable text, while the latter is for variable text. Here we only explain the former, and the latter If you are interested, you can check the text yourself!

The APIs available to us with SpannableString are as follows:

  • BackgroundColorSpanBackground  color
  • ClickableSpan  text is clickable and has click events
  • ForegroundColorSpan  text color (foreground color)
  • MaskFilterSpan  modification effects, such as blur (BlurMaskFilter) and embossing (EmbossMaskFilter)
  • MetricAffectingSpan  parent class, generally not used
  • RasterizerSpan  raster effect
  • StrikethroughSpan  strikethrough (underline)
  • SuggestionSpan  is equivalent to placeholder
  • UnderlineSpanunderline  _
  • AbsoluteSizeSpan  absolute size (text font)
  • DynamicDrawableSpan  sets the image to be aligned based on the text baseline or bottom.
  • ImageSpanPicture  _
  • RelativeSizeSpan  relative size (text font)
  • ReplacementSpan  parent class, generally not used
  • ScaleXSpan  scales based on x-axis
  • StyleSpan  font style: bold, italic, etc.
  • SubscriptSpan  subscript (used in mathematical formulas)
  • SuperscriptSpan  superscript (used in mathematical formulas)
  • TextAppearanceSpan  Text appearance (including font, size, style and color)
  • TypefaceSpan  text font
  • URLSpan  text hyperlink

Well, there are quite a lot. Here is the simplest example. You can search Baidu and Google for other parameter calls~  1) The simplest example:  Operation rendering:

Implementation code:

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        TextView t1 = (TextView) findViewById(R.id.txtOne);
        TextView t2 = (TextView) findViewById(R.id.txtTwo);

        SpannableString span = new SpannableString("Red phone italic strikethrough green underline picture:.");
        //1. Set the background color, the flag that needs to be specified when settingSpan, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE (both before and after)
        span.setSpan(new ForegroundColorSpan(Color.RED), 0, 2, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        //2. Mark text with hyperlinks
        span.setSpan(new URLSpan("tel:4155551212"), 2, 5, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        //3. Mark text with style (italic)
        span.setSpan(new StyleSpan(Typeface.BOLD_ITALIC), 5, 7, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        //4. Mark text with strikethrough
        span.setSpan(new StrikethroughSpan(), 7, 10, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        //5. Mark text with underline
        span.setSpan(new UnderlineSpan(), 10, 16, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        //6. Mark with color
        span.setSpan(new ForegroundColorSpan(Color.GREEN), 10, 13,Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        //7.//Get Drawable resources
        Drawable d = getResources().getDrawable(R.drawable.icon);
        d.setBounds(0, 0, d.getIntrinsicWidth(), d.getIntrinsicHeight());
        //8. Create an ImageSpan and then use ImageSpan to replace the text
        ImageSpan imgspan = new ImageSpan(d, ImageSpan.ALIGN_BASELINE);
        span.setSpan(imgspan, 18, 19, Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
        t1.setText(span);
    }
}

2) Implement a partially clickable TextView.  I believe friends who have played QQ Space and WeChat Moments are familiar with the following stuff. We can click on the corresponding user and then enter to view the user-related information, right?

Let's write a simple example to achieve the following effect:

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        TextView t1 = (TextView) findViewById(R.id.txtOne);

        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < 20; i++) {
            sb.append("Friends" + i + ",");
        }

        String likeUsers = sb.substring(0, sb.lastIndexOf(",")).toString();
        t1.setMovementMethod(LinkMovementMethod.getInstance());
        t1.setText(addClickPart(likeUsers), TextView.BufferType.SPANNABLE);
    }

    //Define a processing method for clicking each part of the text
    private SpannableStringBuilder addClickPart(String str) {
        //Like icon, there is no material here, just find a smiley face to replace it~
        ImageSpan imgspan = new ImageSpan(MainActivity.this, R.drawable.ic_widget_face);
        SpannableString spanStr = new SpannableString("p.");
        spanStr.setSpan(imgspan, 0, 1, Spannable.SPAN_INCLUSIVE_EXCLUSIVE);

        //Create a SpannableStringBuilder object to connect multiple strings
        SpannableStringBuilder ssb = new SpannableStringBuilder(spanStr);
        ssb.append(str);
        String[] likeUsers = str.split(",");
        if (likeUsers.length > 0) {
            for (int i = 0; i < likeUsers.length; i++) {
                final String name = likeUsers[i];
                final int start = str.indexOf(name) + spanStr.length();
                ssb.setSpan(new ClickableSpan() {
                    @Override
                    public void onClick(View widget) {
                        Toast.makeText(MainActivity.this, name,
                                Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void updateDrawState(TextPaint ds) {
                        super.updateDrawState(ds);
                        //Remove the underline and set the font color to blue
                        ds.setColor(Color.BLUE);
                        ds.setUnderlineText(false);
                    }
                },start,start + name.length(),0);
            }
        }
    return ssb.append("Wait" + likeUsers.length + "Personally I think it's great");
    }
}

Operation rendering:

The core is actually just the setting of ClickableSpan~ You can fiddle with the one you write QQ space comments and write one yourself~

2.7 TextView to achieve marquee effect

Let me briefly talk about what a marquee is. It is similar to the web. There is a line of text that keeps scrolling like this. Well, let’s take a look at the implementation renderings. You will understand it at a glance~

Realization renderings:

Code:

<TextView
        android:id="@+id/txtOne"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textSize="18sp"
        android:singleLine="true"
        android:ellipsize="marquee"
        android:marqueeRepeatLimit="marquee_forever"
        android:focusable="true"
        android:focusableInTouchMode="true"
        android:text="You talk about how miserable you are all day long, but you don't come, hehehehehehehehe~"/>

2.8 Set TextView word spacing and line spacing

Just like when we usually write documents, we need to typesetting and set the spacing between lower lines or words, right: TextView in Android can also set up like this:

Word spacing:

android:textScaleX: Controls the horizontal scaling of the font, the default value is 1.0f, the value is float
setScaleX(2.0f) in Java;

Line spacing:  TextView in the Android system will be relatively compact when displaying Chinese by default. In order to maintain the line spacing of each line

android:lineSpacingExtra: Set the line spacing, such as "3dp"  android:lineSpacingMultiplier: Set the multiple of the line spacing, such as "1.2"

It can be set in Java code through:  setLineSpacing method

2.9 Automatic line wrapping

Automatic line wrapping is set through  android:singleLine  , which defaults to false.

If you need automatic line wrapping, you can use:

android:singleLine = "false"

If you want to display it on one line without wrapping, you can use:

android:singleLine = "true"

In addition, you can also set multiple lines to be displayed endlessly, just add the maxLines attribute!

Guess you like

Origin blog.csdn.net/leyang0910/article/details/130931778