Reprint please indicate the source: www.jianshu.com/p/500f7a9ee…
This article is mainly to record the daily development of TextView control, some of the skills used to sort out, only their own development used some points, not comprehensive, not too much technical content. It’s just for the convenience of some programmers when they use it. If you find any mistakes, please help to confirm, thank you!
This article mainly lists the following skills:
- Newline by newline character
- Introduce an image resource into the TextView
- Dynamically transform the image resources in the TextView
- Set the font and style
- Load custom fonts
- Limit the number of TextView characters
- Common in multi-text display [Show all – fold up]
- Price tag with underline
- Text stroke and shadow
- Running horse light effect
- Set word spacing and line spacing
The dynamic diagram of Demo is as follows:
1. Wrap a line with a newline character
The use of line break “\n” is very basic. Sometimes, in some complex itemViews, there will be two rows of TextViews listed to display the content. If the font style of the two rows of TextViews is the same and the data source is fixed or uniform, then you can consider using one TextView. One less TextView to draw, and even the LineaLayout to wrap them around.
Code:
<! -- Plain newline -->
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@color/colorAccent"
android:text="' Study hard \n Day day up" />Copy the code
Effect:
2. Introduce image resources into the TextView
The combination of a picture and several text controls is too common in any project, such as
This can be done by wrapping ImageView+TextView horizontally with LineaLayout, or by embedding the image resource directly into the TextView via the drawableXxx property of the TextView. Xxx refers to the position of the picture, including
- The left drawableLeft
- DrawableRight right
- DrawableTop above
- DrawableBottom below
- DrawableStart Specifies the starting position of the control space
- DrawableEnd The end of the control space
Code:
<TextView
android:id="@+id/tv_drawable"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:drawablePadding="10dp"
android:drawableRight="@drawable/password_hide"
android:gravity="center"
android:text="Click and try it." />Copy the code
Effect:
3. Dynamically transform the picture resources in TextView
Of the two layout methods mentioned above, the horizontal package LinearLayout is slightly bloated, but it is more convenient to dynamically replace the images in it. Directly operate the package’s ImageView. The way TextView inserts images is a little more cumbersome when it comes to dynamically replacing image resources, but it’s also very simple, mainly with Drawable objects.
Code:
//1. Obtain the Drawable object from the image resource
Drawable showPwdDrawable = getResources().getDrawable(R.drawable.password_show);
//2. Set the display range of the Drawable object
showPwdDrawable.setBounds(0.0, showPwdDrawable.getMinimumWidth(), showPwdDrawable.getMinimumHeight());
//3. Set the Drawable to the TextView.
textview.setCompoundDrawables(null.null, showPwdDrawable, null);Copy the code
Effect:
4. Set the font and style
TextView’s Typeface property can be used to set fonts, which have four default types
- normal
- sans
- serif
- monospace
The textStyle property can be used to set styles. By default, there are three types:
- Bold bold
- Italic font
- Normal Normal (default)
Code:
<! -- Bold +serif style -->
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:text="@string/study"
android:textStyle="bold"
android:typeface="serif" />
<! -- Italic + Monospace style -->
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:text="@string/study"
android:textStyle="italic"
android:typeface="monospace" />Copy the code
Effect:
5. Load custom fonts
In addition to the several fonts provided by default, you can also load custom fonts. Note: must be real the vera.ttf Font file (TrueTypeFont) file, or otherwise doesn’t work, or directly behind the Java. Lang. RuntimeException: the Font asset not found abnormal fonts,.
Step: 1. Place the TTF font file in the SRC /main/assets/fonts/ directory of Module 2. Load the font file into memory and set it to TextView
/ / byTypefaceStatic method to load font resources into memoryTypeface typeface = Typeface.createFromasset (getAssets(), "Fonts/Chinese.ttf "); // Set TypeFace toTextView
tvCustomTypeface.setTypeface(typeface);Copy the code
Effect:
6. Limit the number of TextView characters
For UI effects, screen adaptation and other factors, we often need to limit the number of words displayed by the TextView, which can be easily done with three attributes:
- Ellipsize ellipses the position
- MaxEms Maximum number of characters. One Chinese character is 1 character, and one English/symbol is half a character. Replace with ellipsis from maxEms+1
- MaxLines line limit (singleLine also works, but has been marked Deprecated)
<! -- Limit number of characters -->
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ellipsize="end"
android:maxLines="1"
android:maxEms="Seven"
android:text="@string/study" />Copy the code
Effect:
7. Common in multi-text display [Show all – fold up]
“More” or “Show all” is displayed at the end of the page, and the text will be displayed at the end of the page.
The setMaxLines(int maxLines) method can achieve the purpose.
Each time you click the [Show All – Fold] button, execute the following event to achieve. See the GIF at the beginning of this article.
showAll =!showAll;
if(showAll){
tvShowAll.setMaxLines(2);
BtnShowAll. SetText (" View all "); }else {
tvShowAll.setMaxLines(20);
BtnShowAll. SetText (" folded up "); }Copy the code
Pay attention to
When encountering the above problems in the development, there must be a premise scenario at the same time, that is, according to the data content to dynamically determine the display [show all] button.
In this case, we need to dynamically obtain how many lines the textView takes up after loading the content. For example, we need to specify more than 3 lines, at the end of the omit + display [display more]. You need to use the getLineCount() method of the TextView.
GetLineCount () returns the number of lines of text, or 0 if the internal Layout has not been built. Returns the number of lines of TextView content, or 0 if there is no content
Note that this method cannot be called directly from onCreate(), because the TextView may not have finished loading and the number of rows retrieved is zero. The Show All button can be determined as follows
textview.post(new Runnable() {
@Override
public void run(a) {
if(textview.getLineCount() > 3) {// The contents of the textView are larger than the line limit, show the [Show All] button"
}else {
// The contents of the textView are less than or equal to the line limit.}}});Copy the code
8. Price tags and underlining
The commodity transaction module is bound to involve the commodity price, and generally for the purpose of promotion, the original price and the current price of the commodity will be displayed on the interface, the original price is much higher than the current price, and then the original price is marked with a horizontal line to indicate the cancellation to stimulate customer consumption. This is a very common price promotion UI.
This effect requires the TextView to be drawn with a Paint object. The system is already wrapped so we can simply use it.
The first step is to define the XML normally
<! -- Price tag -->
<! -- Middle line -->
<TextView
android:id="@+id/tv_line_middle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="¥20.00"
android:textColor="@android:color/holo_red_dark" />
<! -- Bottom line -->
<TextView
android:id="@+id/tv_line_end"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:text="¥20.00"
android:textColor="@android:color/holo_red_dark" />Copy the code
The second step is to draw lines from the TextView Paint object
// Middle line
tvLineMiddle.getPaint().setFlags(Paint. STRIKE_THRU_TEXT_FLAG );
/ / the underline
tvLineEnd.getPaint().setFlags(Paint.UNDERLINE_TEXT_FLAG);Copy the code
Effect:
9. Text Stroke and shadow
Attributes involved:
- shadowColor : Place a blurred shadow of text underneath the text, drawn with the specified color. Draws a blurred shadow under the text with the specified color
- shadowDx Horizontal offset of the text shadow. Horizontal/horizontal offset of the text shadow
- shadowDy Vertical offset of the text shadow. The vertical/vertical offset of the text shadow
- shadowRadius Blur radius of the text shadow. The radius of the shadow
<! -- Text Stroke and Shadow -->
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:shadowColor="#ff0000"
android:shadowDx="5"
android:shadowDy="5"
android:shadowRadius="5"
android:text="@string/study" />Copy the code
Effect:
10. Horse light effect
Now this effect is used less and less, not to mention.
Directly on the code, the effect picture see the top of the article GIF:
<! -- Running light effect -->
<TextView
android:layout_width="200dp"
android:layout_height="wrap_content"
android:background="@android:color/holo_blue_light"
android:ellipsize="marquee"
android:focusable="true"
android:focusableInTouchMode="true"
android:marqueeRepeatLimit="marquee_forever"
android:singleLine="true"
android:text="@string/poem" />Copy the code
11. Set word spacing and line spacing
Attributes involved:
- LetterSpacing word spacing
- Must be a floating point value, such as “0.2”. (0.0~1.0 stands for a letter) —– Must be a decimal between 0.0 and 1.0, using one letter as the space standard
- LineSpacingExtra spaced
- Must be a dimension value, which is a floating point number appended with a unit such as “14.5sp”. Available units are: px (pixels), dp (density-independent pixels), sp (scaled pixels based on preferred font size), in (inches), Mm (millimeters). —– specify row spacing directly via px,dp, SP, for example 14.5sp
- LineSpacingMultiplier Multiple of row spacing
- Must be a floating point value, such as “1.2”.—- e.g. 1.2 times
Directly use the above properties, you can achieve the purpose of setting the word spacing, line spacing, the code is as follows, see the effect picture at the top of the article GIF
<! -- Word spacing 0.5 characters -->
<TextView
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:background="@android:color/darker_gray"
android:letterSpacing="0.5"
android:text="@string/poem" />
<! -- Line spacing 10sp-->
<TextView
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:background="@android:color/holo_green_light"
android:lineSpacingExtra="10sp"
android:text="@string/poem" />
<! -- 1.8x line spacing -->
<TextView
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:lineSpacingMultiplier="1.8"
android:text="@string/poem" />Copy the code
Demo Download Address