TextView (text box) detailed explanation
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. What this section brings to you The UI control is: TextView (text box), a control used to display text. Another point to declare is that I am not translating the API documentation, and I will not deduct the attributes one by one. I only learn the commonly used and useful ones in actual development. Everyone encounters them. If you find unfamiliar attributes, you can query the corresponding API! Of course, the link to the API document corresponding to this section will be posted at the beginning of each section: 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. This is related to the device hardware. Generally, we recommend using this to support WVGA, HVGA and QVGA, which does not rely on pixels. px: pixels. Different devices have the same display effect. Generally, our 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 several of the most basic attributes:
Layout code:
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="../style/images/android-tutorial-textview.html">
<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="../style/images/android-tutorial-textview.html"
android:textSize="18sp" />
</RelativeLayout>
The above TextView has the following attributes:
id: Set a component id for TextView. Based on the id, we can use it in the Java code Obtain the object through the findViewById() method, and then set the relevant attributes, 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 content displayed by the control, It depends on the size of 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. For example, for the sake of display effect, I set it to 200dp here.
layout_height: The width 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 characters through @String/xxx For string content, I will write it directly in "" for convenience. It is not recommended to write it like this! ! !
textColor: Set the font color, the same as above, reference it 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 can be understood as the color that fills the entire control, which can be a picture!
2. Actual development example
2.1 TextView with shadow
Several properties involved:
android:shadowColor:Set the shadow color, you need to use it with shadowRadius!
android:shadowRadius:Settings The blur degree of the shadow, set to 0.1, becomes the font color. It is recommended to use 3.0
android:shadowDx: to set the offset of the shadow in the horizontal direction, that is The abscissa position of the start of the horizontal shadow
##android:shadowDy: Set the offset of the shadow in the vertical direction, which is the ordinate position of the start of the vertical shadow
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, ordinary rectangular border or 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 yourself! Then TextView will blackgroung Just set it 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
paddingandroid:width = "xdp" android:color="xxx"> This is Set the thickness of the border and the color of the border
##<- 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:
Implementation renderings:startColor: starting color endColor: ending color centerColor: middle Colorangle: Direction angle, when equal to 0, from left to right, then counterclockwise, when angle = 90 degrees, from bottom to toptype: Set the type of gradient
Code implementation:
Step 1: Write the Drawable of the rectangular border :<shape xmlns:android="http://schemas.android.com/apk/res/ android" >
<!-- Set a black border -->
<stroke android:width="2px" android:color="../style/images/android- tutorial-textview.html"/>
; !-- Gradient -->
## android: Startcolor = "#FCD209"/& GT;
& LT;! Set the border distance to make the space larger-& gt;
& lt; padding
android: left = "5dp" "
android:top="5dp"
android:right="5dp"
android:bottom="5dp"/>
</shape>
Step 2: Write a Drawable with a rounded rectangle border:
<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=" ../style/images/android-tutorial-textview.html" />
<!-- Set the radius of the four rounded corners -->
<corners
android:bottomLeftRadius= "10px"
android:bottomRightRadius="10px"
android:topLeftRadius="10px"
android:topRightRadius="10px" />
<!-- Set the margins and let A little more space -->
<padding
android:bottom="5dp"
android:left="5dp"
android:right="5dp"
android:top= "5dp" />
</shape>
Step 3:将TextView的blackground属性设置成上面这两个Drawable:
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="../style/images/android-tutorial-textview.html"
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="../style/images/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="../style/images/txt_radiuborder"
android:text="圆角边框的TextView" />
</LinearLayout>
2.3 TextView with picture (drawableXxx):
In actual development, we may encounter this demand:
As shown in the figure, To achieve this effect, your idea may be: an ImageView for displaying pictures + a TextView for displaying text, and then throw them into a LinearLayout, then create four such small layouts in sequence, and then put them into another 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 spacing between pictures and text!
Rendering: (Set pictures in four directions)
##Implementation code:
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 questions: You may find that the drawable we set up 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:
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]);
}
}
Running renderings:
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); After obtaining the resources, you can call setBounds to set the upper left and lower right coordinate points. For example, the settings here represent: The length is: from 100dp to 200dp from the far left of the text The width is: 200dp extending upward 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, use null instead! PS: In addition, as seen from the above, we can also directly call setCompoundDrawables in Java code as TextView sets the picture!
2.4 Use the autoLink attribute to identify the link typeWhen URL, E-Mail, phone number, and map appear in the text, we You can set the autoLink attribute; when we click The corresponding part of the text can jump to a default APP, such as a series of numbers. Click to jump to the dialing interface! Look at the rendering: all means all are included, and the protocol header is automatically recognized~ In Java code, you can call setAutoLinkMask(Linkify.ALL); You don’t need to write the protocol header at this time, autolink will automatically recognize it, but you still need to set it for this TextView: setMovementMethod(LinkMovementMethod.getInstance()); Otherwise, clicking will have no effect!
2.5 TextView plays with HTML
As the title says, in addition to displaying ordinary text, TextView also predefines some HTML-like tags. Through these tags, we can use TextView displays different font colors, sizes, fonts, and even displays pictures, links, etc.! We just use some of the HTML Tags, plus the support of the android.text.HTML class, can 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 font size small
- i
<><b>: Italic bold
- a
<>:Connect 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.
Then set it up. If we need corresponding settings, we need to set them up for TextView and call the following method: Java
setMovementMethod(LinkMovementMethod.getInstance())
Well, let’s write code to try:
1) Test text and hyperlink tags
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)find ViewById( ( ";
s1 += "<a href = 'http://www.baidu.com'>Baidu</a>";
t1.setText(Html.fromHtml(s1));
t1.setMovementMethod(LinkMovementMethod.getInstance());
}
}
Running renderings:
Well, the test is completed~
2) Test the src tag and insert the picture:
Look at the running effect diagram:
Next, let’s look at the implementation code. The implementation code looks a bit complicated and uses reflection (by the way, don’t forget Put an icon picture in the drawable directory! ):
@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, you can In addition to customizing the style of our TextView, you can also use 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. If you are interested in the latter, you can check it out by yourself. text!
SpannableString The APIs available to us are as follows:
Okay, there are quite a lot. Here is the simplest example. For other parameter calls, you can search on Baidu and Google~
BackgroundColorSpan Background color
ClickableSpan The text is clickable and there is a click event
ForegroundColorSpan Text color (foreground color)
MaskFilterSpan Modification effects, such as blur (BlurMaskFilter), embossing (EmbossMaskFilter)
MetricAffectingSpan Parent class, general No use
RasterizerSpan Raster effect
StrikethroughSpan Strikethrough (underline)
SuggestionSpan Equivalent to placeholder
UnderlineSpan Underline
AbsoluteSizeSpan Absolute size (text font)
DynamicDrawableSpan Sets the image to be aligned based on the text baseline or bottom.
ImageSpan Image
RelativeSizeSpan Relative size (text font)
ReplacementSpan Parent class, generally not used
ScaleXSpan Scaling 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
1) The simplest example: Running renderings:
Implementation code:@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 oblique delete line green subordinate picture:.");
// 1. Set background color, when setspan, you need to specify the flag, spanned.span_exclusive_exclusive (not included 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 (italic) with style
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 that friends who have played QQ space and WeChat Moments are not unfamiliar with the following stuff, we can click The corresponding user then enters to view user-related information, right?
Let’s write a simple example to achieve the following effect:
@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 + ",");
}
sb.substring(0, sb.lastIndexOf(", ")). toString();
t1.setMovementMethod(LinkMovementMethod.getInstance());
t1.setText(addClickPart(likeUsers), TextView.BufferType.SPANNABLE);
}
//Definition A 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 instead~
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 and 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 (); IC Void Updatedrawstate (TextPaint ds) {
(Color.BLUE);
ds.setUnderlineText(false) ;
}
Personally feel great");
}
}
Operation renderings:
The core is actually: the setting of ClickableSpan~ You can fiddle with the one that writes QQ space comments and write one yourself~
2.7 TextView to realize the marquee effect
Let’s 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. The implementation renderings can be understood at a glance~
Implementation renderings:
Code implementation:
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've been talking about being a fool all day long, but you didn't come, hehehehehehehehe~"/>
2.8 Set TextView word spacing and line spacing
Just like when we usually write documents, we need to typesetting, set the spacing between the lower lines or words, right: TextView in Android can also be set like this:
Character spacing:
android:textScaleX:调节字间距的,默认值1.0f,值是float Java中setScaleX(2.0f);
Line spacing: When TextView in Android system displays Chinese by default It will be more compact, in order to maintain the line spacing of each line
android:lineSpacingExtra:Set the line spacing, such as "3dp"android:lineSpacingMultiplier:Settings Multiples of line spacing, such as "1.2"
In Java code, you can set it through:setLineSpacingmethod
2.9 Automatic line wrapping
automatic Line breaks are set via android:singleLine, which defaults to false.
If you need to automatically wrap the line, 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 If the lines cannot be displayed, just add the maxLines attribute!
3. Summary of this section:
This section provides a detailed analysis of the TextView control in Android and provides solutions to some common problems in development. I believe It will bring great convenience to your actual development. In addition, the author's ability is limited, so what I write may have some flaws. You are welcome to point out. Thank you very much ~ In addition, please indicate the source when reprinting: coder-pig! Thank you~