2.3.1 TextView (Text Box) Detailed Explanation
Category Android Basic Tutorial
Introduction to This Section:
>
After learning about the six major layouts in Android, starting from this section, we will explain the UI components in Android one by one. The UI component we are introducing in this section is: TextView (Text Box), a component used to display text. Additionally, I would like to state that I am not translating API documentation and will not go through each property one by one. I will only focus on the commonly used and useful properties in actual development. If you encounter unfamiliar properties, you can refer to the corresponding API! Of course, at the beginning of each section, I will post the link to the API documentation for this section: TextView API. Before starting the content of this section, I would like to introduce a few units:
dp(dip): device independent pixels. Different devices have different display effects, which is related to the device hardware. Generally, we recommend using this to support WVGA, HVGA, and QVGA, which is not dependent on pixels. px: pixels. The display effect is the same on different devices, and we usually represent HVGA as 320x480 pixels, which is used more frequently. pt: point, a standard length unit, 1pt = 1/72 inches, used in the printing industry, very simple and easy to use; sp: scaled pixels. Mainly used for text size display, best for textsize.
1. Detailed Explanation of Basic Properties:
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 (Display Box)"
android:textColor="#EA5246"
android:textStyle="bold|italic"
android:background="#000000"
android:textSize="18sp" />
</RelativeLayout>
The above TextView has the following properties:
-id: Sets a component id for the TextView. Based on the id, we can obtain the object in the Java code through the findViewById() method, and then set related properties. Or when using RelativeLayout, the reference component is also used by id!
-layoutwidth: The width of the component, usually written as: wrapcontent or matchparent(fillparent), the former is as large as the content displayed by the control, 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 I set it to 200dp here for display effect.
-layout_height: The height of the component, the content is the same as above.
-gravity: Sets the alignment direction of the content in the control, the text in TextView, the picture in ImageView, etc.
-text: Sets the displayed text content. Generally, we write the string to the string.xml file, and then obtain the corresponding string content through @String/xxx. Here, for convenience, I wrote it directly in "", which is not recommended!
-textColor: Sets the font color, as above, referenced through colors.xml resources, do not write it directly like this!
-textStyle: Sets the font style, three optional values: normal (no effect), bold (bold), italic (italic)
-textSize: Font size, the unit is generally used in sp!
-background: The background color of the control, which can be understood as the color that fills the entire control, and it can be an image!
2. Practical Development Examples
2.1 TextView with Shadow
The properties involved are:
-android:shadowColor: Sets the shadow color, needs to be used with shadowRadius!
-android:shadowRadius: Sets the blur level of the shadow, setting it to 0.1 becomes the font color, it is recommended to use 3.0
-android:shadowDx: Sets the horizontal offset of the shadow, that is, the x-coordinate position where the horizontal
<TextView
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 corners border" />
2.3 TextView with Images (drawableXxx):
In actual development, we may encounter this requirement:
As shown in the figure, to achieve this effect, you might think: an ImageView for displaying images + a TextView for displaying text, then put them into a LinearLayout, and then create four such small layouts, and put them into a larger LinearLayout, the effect can be achieved, but is it a bit cumbersome? And we also mentioned before that the fewer the layout hierarchy, 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 the image is actually: drawableXxx; you can set images in four directions: drawableTop (top), drawableButtom (bottom), drawableLeft (left), drawableRight (right). In addition, you can also use drawablePadding to set the spacing between the image and the text!
Effect Picture: (Set images in all 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 Quan Egg" />
</RelativeLayout>
Some Issues: You may find that the drawable we set 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!
Example 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();
// Array subscript 0~3, in turn is: left, top, right, bottom
drawable[1].setBounds(100, 0, 200, 200);
txtZQD.setCompoundDrawables(drawable[0], drawable[1], drawable[2],
drawable[3]);
}
}
Running effect picture:
Code Analysis:
>
①Drawable[] drawable = txtZQD.getCompoundDrawables(); Get the four different direction image resources, array elements in turn are: left, top, right, bottom images
②drawable[1].setBounds(100, 0, 200, 200); Then after obtaining the resources, you can call setBounds to set the coordinates of the top, right, bottom, for example, here it represents: Length is: from 100dp away from the leftmost part of the text to 200dp Width is: extending 200dp upwards from 0dp above the text!
③txtZQD.setCompoundDrawables(drawable[0], drawable[1], drawable[2], drawable[3]); Re-set the drawable array for TextView! You can use null instead of no picture! PS: In addition, from the above, we can also directly call setCompoundDrawables in the Java code to Set pictures for TextView!
2.4 Use the autoLink attribute to recognize link types
When a URL, E-Mail, 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 series of numbers, click and jump to the dial interface!
See the effect picture:
all is to include everything, automatically 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 an image, and the image will jump when clicked.
### 2.6 Customizing Text with SpannableString & SpannableStringBuilder
>
In addition to the HTML mentioned above, which can customize the style of our TextView, we can also use SpannableString and SpannableStringBuilder to accomplish this. The difference between the two is that the former is for immutable text, while the latter is for mutable text. Here, I will only explain the former, and if you are interested in the latter, you can look it up yourself!
The following APIs are available for us to use with SpannableString:
>
-**BackgroundColorSpan** Background color
-**ClickableSpan** Text is clickable, with click events
-**ForegroundColorSpan** Text color (foreground)
-**MaskFilterSpan** Decoration effects, such as blur (BlurMaskFilter), emboss (EmbossMaskFilter)
-**MetricAffectingSpan** Parent class, generally not used
-**RasterizerSpan** Raster effect
-**StrikethroughSpan** Strikethrough (middle line)
-**SuggestionSpan** Equivalent to a placeholder
-**UnderlineSpan** Underline
-**AbsoluteSizeSpan** Absolute size (text font)
-**DynamicDrawableSpan** Set image, aligned based on the text baseline or bottom.
-**ImageSpan** Image
-**RelativeSizeSpan** Relative size (text font)
-**ReplacementSpan** Parent class, generally not used
-**ScaleXSpan** Scale based on the 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 few, so here's the simplest example, and you can search Baidu or Google for other parameters. **1) The simplest example:** Running effect picture:
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 call italic strikethrough green underline image:.");
//1. Set background color, when setSpan you need to specify the flag, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE (neither before nor after)
span.setSpan(new ForegroundColorSpan(Color.RED), 0, 2, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
//2. Mark the text with a hyperlink
span.setSpan(new URLSpan("tel:4155551212"), 2, 5, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
//3. Mark the text with style (italic)
span.setSpan(new StyleSpan(Typeface.BOLD_ITALIC), 5, 7, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
//4. Mark the text with a strikethrough
span.setSpan(new StrikethroughSpan(), 7, 10, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
//5. Mark the text with an underline
span.setSpan(new UnderlineSpan(), 10, 16, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
//6. Mark the text with color
span.setSpan(new ForegroundColorSpan(Color.GREEN), 10, 13, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
//7. // Get Drawable resource
Drawable d = getResources().getDrawable(R.drawable.icon);
d.setBounds(0, 0, d.getIntrinsicWidth(), d.getIntrinsicHeight());
//8. Create ImageSpan, then replace the text with ImageSpan
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 with QQ Space and WeChat Moments are not unfamiliar with the following things, right? We can click on the corresponding user and then enter to view the user's related information!
Next, let's
}, start, start + name.length(), 0);
}
}
return ssb.append("and " + likeUsers.length + " others think it's awesome");
}
Running effect picture:
The core is actually just the setting of ClickableSpan~ You can try to write your own QQ space comment~
2.7 Implementing a Marquee Effect TextView
To briefly explain what a marquee is, it's like a web page where a line of text keeps rolling continuously, okay, or just take a look at the implementation effect picture, and you'll understand at a glance~
Implementation effect picture:
Code implementation:
<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 always say you've had a bad day, but you didn't come, hehehehehehehe~"/>
2.8 Setting the Letter Spacing and Line Spacing of TextView
Just like when we usually write documents, we need to typeset and set the spacing between lines or letters, right: Android's TextView can also be set like this:
Letter spacing:
android:textScaleX: Controls the horizontal scaling of the font, with a default value of 1.0f, and the value is a float
Java setScaleX(2.0f);
Line spacing: Android system TextView displays Chinese characters more compactly by default, in order to keep the line spacing for each line
>
android:lineSpacingExtra: Sets the line spacing, such as "3dp" android:lineSpacingMultiplier: Sets the multiple of the line spacing, such as "1.2"
In Java code, you can set it through the setLineSpacing method
2.9 Automatic Line Wrapping
Automatic line wrapping is set by android:singleLine, the default is false.
If you need automatic line wrapping, you can use:
android:singleLine = "false"
If you want to display in one line without wrapping, you can use:
android:singleLine = "true"
In addition, you can also set multiple lines that are not displayed completely, just add a maxLines attribute!
3. Summary of this section:
This section provides a detailed analysis of the TextView control in Android, offering solutions to common problems encountered in development, which will bring great convenience to your actual development. In addition, the author's ability is limited, and there may be some errors in the written content, please point out, I am very grateful~ Also, please indicate the source: coder-pig! Thank you~
-1.0.1 2015 Latest Android Basic Tutorial Catalog
-1.1 Background and System Architecture Analysis
-1.2 Development Environment Construction
-1.2.1 Developing Android APP with Eclipse + ADT + SDK
-1.2.2 Developing Android APP with Android Studio
-1.3 SDK Update Problem Solving
-1.4 Genymotion Simulator Installation
-1.5.1 Git Tutorial on Basic Operations of Local Repository
-1.5.2 Git Using GitHub to Set Up a Remote Repository
-1.6 How to Play with 9 (Nine Sister) Images
-1.7 Interface Prototype Design
-1.8 Project Related Analysis (Various Files, Resource Access)
-1.9 Android Program Signing and Packaging
-1.11 Decompiling APK to Obtain Code & Resources
-2.1 The Concept of View and ViewGroup
-2.2.1 LinearLayout (Linear Layout)
-[2.2.2 RelativeLayout (Relative Layout)](android-
3.6 Responding to System Configuration Events (Configuration Class)
4.4.2 Further Exploration of ContentProvider - Document Provider
5.2.1 Detailed Explanation of Fragments - Implementing Bottom Navigation Bar (Method 1)
5.2.2 Detailed Explanation of Fragments - Implementing Bottom Navigation Bar (Method 2)
5.2.3 Detailed Explanation of Fragments - Implementing Bottom Navigation Bar (Method 3)
5.2.4 Detailed Explanation of Fragments - Bottom Navigation Bar + ViewPager for Page Swiping
6.2 Data Storage and Access - SharedPreferences for Saving User Preferences
7.1.1 What to Learn in Android Network Programming and Http Protocol
7.1.2 Learning about Android Http Request and Response Headers
[7.6.1 Preparing for Socket Learning with Network Basics](android-tutorial-socket-intro.html
8.4.4 Android Animation Collection: Property Animation - Again
11.0 "2015 Latest Android Basic Tutorial" Concludes with Confetti~
12.2 DrySister Girl Viewing App (First Edition) - 2. Parsing Backend Data
12.4 DrySister Girl Viewing App (First Edition) - 4. Adding Data Caching (Integrating SQLite)