Android Learning Road (4) Text Box of UI Controls

The UI control brought to you in this section is: TextView (text box), a control used to display text. In addition, I declare that I am not translating API documents, and I will not deduct attributes one by one. I only learn what is commonly used in actual development. Yes, useful, you can query the corresponding API when encountering unfamiliar attributes! Of course, at the beginning of each section, a link to the API documentation corresponding to this section will be posted: TextView API

Well, before starting this section, let’s introduce the following units: dp (dip): device independent pixels (device independent pixels). Different devices have different display effects, which are related to the device hardware. Generally, we support This is recommended for WVGA, HVGA, and QVGA, independent of pixels. px: pixels (pixels). Different devices have the same display effect. Generally, our HVGA represents 320x480 pixels, which is used more. 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, let's understand a few of the most basic properties:

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(显示框)"
        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. According to the id, we can get the object through the findViewById() method in the Java code, and then set related properties, or when using RelativeLayout, the reference component also uses the id!
  • layout_width: Width of the component, generally write: wrap_content or match_parent(fill_parent) , the former is how big the content displayed by the control is, the size of the control is, and the latter will fill the parent container where the control is located; of course, it can also be set to a specific size, such as In order to display the 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 directly write it into "" here, which is not recommended Write like this! ! !
  • textColor: Set the font color, same as above, referenced by the colors.xml resource, don't write like this directly!
  • textStyle: set the font style, three optional values: normal (no effect), bold (bold), italic (italic)
  • textSize: font size, the unit is generally sp!
  • background: The background color of the control, which can be understood as the color that fills the entire control, which can be a picture!

2. Actual development examples

2.1 TextView with shadow

Several attributes involved:

  • android:shadowColor: Set the shadow color, it needs to be used together with shadowRadius!
  • android:shadowRadius: Set the fuzziness of the shadow. If it is set to 0.1, it will become 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 shadow starts in the horizontal direction
  • 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

Renderings:

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"
        android:textColor="#4A4AFF"
        android:textSize="30sp" />

2.2 TextView with border:

If you want to set a border background for TextView, normal rectangle border or round corner 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 realization principle is very simple, write a ShapeDrawable resource file by yourself! Then TextView sets blackgroung as this drawable resource!

Briefly talk about several nodes and attributes of the shapeDrawable resource file:

  • This is to set the background color
  • This is to set the thickness of the border and the color of the border
  • <padding androidLbottom = “xdp”…> This is to set the margin
  • <corners android:topLeftRadius="10px"...> This is to set the rounded corners
  • This is to set the gradient color, the optional attributes are: startColor: start color endColor: end color centerColor: middle color angle: direction angle, when equal to 0, from left to right, then turn counterclockwise, when angle = 90 degrees When from bottom to top type: set the type of gradient

Realize the effect diagram:

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" >

    <!-- 设置一个黑色边框 -->
    <stroke android:width="2px" android:color="#000000"/>
    <!-- 渐变 -->
    <gradient
        android:angle="270"
        android:endColor="#C0C0C0"
        android:startColor="#FCD209" />
    <!-- 设置一下边距,让空间大一点 -->
    <padding
        android:left="5dp"
        android:top="5dp"
        android:right="5dp"
        android:bottom="5dp"/>

</shape> 

Step 2: Write the Drawable of the rounded rectangle border:

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

    <!-- 设置透明背景色 -->
    <solid android:color="#87CEEB" />

    <!-- 设置一个黑色边框 -->
    <stroke
        android:width="2px"
        android:color="#000000" />
    <!-- 设置四个圆角的半径 -->
    <corners
        android:bottomLeftRadius="10px"
        android:bottomRightRadius="10px"
        android:topLeftRadius="10px"
        android:topRightRadius="10px" />
    <!-- 设置一下边距,让空间大一点 -->
    <padding
        android:bottom="5dp"
        android:left="5dp"
        android:right="5dp"
        android:top="5dp" />
        
</shape>

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

<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" />

    <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" />


</LinearLayout>

2.3 TextView with pictures (drawableXxx):

In actual development, we may encounter this requirement:

As shown in the picture, to achieve this effect, your idea may be: an ImageView is used to display pictures + a TextView is used to display text, and then throw them into a LinearLayout, and then create four such small layouts in turn, and then 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 meet 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="张全蛋" />  
  
</RelativeLayout> 

Some problems: You may find that the drawable we set up in this way 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();  
        // 数组下表0~3,依次是:左上右下  
        drawable[1].setBounds(100, 0, 200, 200);  
        txtZQD.setCompoundDrawables(drawable[0], drawable[1], drawable[2],  
                drawable[3]);  
    }  
} 

Running effect diagram:

Code analysis:

  • ①Drawable[] drawable = txtZQD.getCompoundDrawables( ); Get picture resources in four different directions, and the array elements are: top left and right bottom pictures
  • ②drawable[1].setBounds(100, 0, 200, 200); Then, after obtaining the resources, you can call setBounds to set the upper left and right lower coordinate points. For example, the settings here represent: The length is: 100dp from the far left of the text The width to 200dp is: extending 200dp from 0dp above the text!
  • ③txtZQD.setCompoundDrawables(drawable[0], drawable[1], drawable[2], drawable[3]); reset the drawable array for TextView! No picture can be replaced by null! PS: In addition, we can also see from the above 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 there are URLs, E-Mails, phone numbers, and maps 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 dial interface!

Look at the renderings:

all means everything is included, and the protocol header is automatically recognized~ You can call setAutoLinkMask(Linkify.ALL) in the Java code; at this time, you don’t need to write the protocol header, and autolink will automatically recognize it, but you also need to set this TextView: setMovementMethod(LinkMovementMethod.getInstance ()); Otherwise, clicking will have no effect!

2.5 TextView play with HTML

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

PS: Of course, not all tags are supported, and the following are commonly used:

  • : Set the color and font.
  • : set font size
  • : set font size small
  • : italic bold
  • : Connection URL
  • :picture

If you setText directly, it is useless. We need to call the Html.fromHtml() method to convert the string to the CharSequence interface, and then set it. If we need to set it accordingly, we need to set it for TextView. Call the following method: Java setMovementMethod (LinkMovementMethod. getInstance())

Well, then we 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>百度一下,你就知道~:</b></font><br>";
        s1 += "<a href = 'http://www.baidu.com'>百度</a>";
        t1.setText(Html.fromHtml(s1));
        t1.setMovementMethod(LinkMovementMethod.getInstance());
    }
}

Running effect diagram:

Well, the test is over~

2) Test the src tag and insert a picture:

Look at the running effect diagram:

Next, let's look at the implementation code. The implementation code looks a bit complicated, and reflection is used (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 = "图片:<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));
    }
}

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

2.6 SpannableString&SpannableStringBuilder custom 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: 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 that SpannableString can use for us are as follows:

  • BackgroundColorSpan background color
  • ClickableSpan text is clickable and has a click event
  • ForegroundColorSpan text color (foreground color)
  • MaskFilterSpan modification effects, such as blur (BlurMaskFilter), relief (EmbossMaskFilter)
  • MetricAffectingSpan parent class, generally not used
  • RasterizerSpan raster effect
  • StrikethroughSpan strikethrough (in dash)
  • SuggestionSpan is equivalent to a placeholder
  • UnderlineSpan underline
  • AbsoluteSizeSpan absolute size (text font)
  • DynamicDrawableSpan sets the picture, based on the text baseline or bottom alignment.
  • ImageSpan image
  • RelativeSizeSpan relative size (text font)
  • ReplacementSpan parent class, generally not used
  • ScaleXSpan scales based on the x-axis
  • StyleSpan font styles: bold, italic, etc.
  • SubscriptSpan subscript (mathematical formula will be used)
  • SuperscriptSpan superscript (math formula will be used)
  • 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, other parameters can be called by Baidu and Google~ 1) The simplest example: Running effect diagram:

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("红色打电话斜体删除线绿色下划线图片:.");
        //1.设置背景色,setSpan时需要指定的flag,Spanned.SPAN_EXCLUSIVE_EXCLUSIVE(前后都不包括)
        span.setSpan(new ForegroundColorSpan(Color.RED), 0, 2, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        //2.用超链接标记文本
        span.setSpan(new URLSpan("tel:4155551212"), 2, 5, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        //3.用样式标记文本(斜体)
        span.setSpan(new StyleSpan(Typeface.BOLD_ITALIC), 5, 7, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        //4.用删除线标记文本
        span.setSpan(new StrikethroughSpan(), 7, 10, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        //5.用下划线标记文本
        span.setSpan(new UnderlineSpan(), 10, 16, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        //6.用颜色标记
        span.setSpan(new ForegroundColorSpan(Color.GREEN), 10, 13,Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        //7.//获取Drawable资源
        Drawable d = getResources().getDrawable(R.drawable.icon);
        d.setBounds(0, 0, d.getIntrinsicWidth(), d.getIntrinsicHeight());
        //8.创建ImageSpan,然后用ImageSpan来替换文本
        ImageSpan imgspan = new ImageSpan(d, ImageSpan.ALIGN_BASELINE);
        span.setSpan(imgspan, 18, 19, Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
        t1.setText(span);
    }
}

2) Realize part of the clickable TextView. I believe that friends who have played Qzone and WeChat Moments are no strangers to the following stuff. We can click on the corresponding user and enter to view 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("好友" + i + ",");
        }

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

    //定义一个点击每个部分文字的处理方法
    private SpannableStringBuilder addClickPart(String str) {
        //赞的图标,这里没有素材,就找个笑脸代替下~
        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);

        //创建一个SpannableStringBuilder对象,连接多个字符串
        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);
                        //删除下划线,设置字体颜色为蓝色
                        ds.setColor(Color.BLUE);
                        ds.setUnderlineText(false);
                    }
                },start,start + name.length(),0);
            }
        }
    return ssb.append("等" + likeUsers.length + "个人觉得很赞");
    }
}

Running effect diagram:

The core is actually: the setting of ClickableSpan, you can fiddle with the one who wrote the Qzone comment and write one yourself

2.7 TextView to realize marquee effect

Briefly, what is a marquee? It is similar to the web. There is a line of words that keeps scrolling in circles. Well, let’s take a look at the implementation effect diagram, and you can understand it at a glance~

Realize the effect diagram:

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="你整天说着日了狗日了狗,但是你却没有来,呵呵呵呵呵呵呵呵呵呵~"/>

2.8 Set TextView word spacing and line spacing

Just like when we usually write a document, we need to typesetting, set the spacing between the next line or the word: TextView in Android can also be set like this:

Word spacing:


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

Line spacing: TextView in the Android system will be relatively compact when displaying Chinese by default. In order to keep 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"

Java code can be set by: setLineSpacing method

2.9 Word Wrap

Automatic line wrapping is set by android:singleLine, the default is false.

If you need to wrap automatically, you can use:

android:singleLine = “false”

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

android:singleLine = “true”

In addition, you can also set multiple lines to display endlessly, just add a maxLines attribute!

Guess you like

Origin blog.csdn.net/qq_32907491/article/details/132266617