TextView

Typeface

有三种不同的默认字体,称为Droid系列字体:sans,monospace和serif。 您可以指定其中任何一个作为XML中的android:typeface属性的值:

typeface.png

Text Style

android:textStyle属性可以用来强调文本。 可能值为:normal,bold,italic。

text-style.png

Text Truncation

首先为了限制文本行的总数,我们可以使用android:maxLinesandroid:minLines

<TextView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:minLines="1"
    android:maxLines="2"
/>

ellipsize属性的值:start、end、middle 、marquee 。

Text Shadow

  • android:shadowColor - 阴影颜色与textColor类似
  • android:shadowRadius - 阴影的半径
  • android:shadowDx - 阴影的水平偏移量
  • android:shadowDy - 阴影的垂直偏移量
text-shadow.png

其他属性

  • android:includeFontPadding:删除大字体附加的填充。
  • android:lineSpacingMultiplier:管理行间距,默认为“1”。

插入HTML格式

TextView本身就支持HTML,通过将HTML标记转换为View的Spannable节点。例如:

TextView view = (TextView)findViewById(R.id.sampleText);
String formattedText = "This <i>is</i> a <b>test</b> of <a href='http://foo.com'>html</a>";
// or getString(R.string.htmlFormattedText);
view.setText(Html.fromHtml(formattedText));
text-html.png

更多

设置字体颜色——<font>

Html.fromHtml("Nice! <font color='#c5c5c5'>This text has a color</font>. This doesn't"); 

存储长字符串——CDATA

<?xml version="1.0" encoding="utf-8"?>
<string name="htmlFormattedText">
    <![CDATA[
        Please <a href="http://highlight.com">let us know</a> if you have <b>feedback on this</b> or if 
        you would like to log in with <i>another identity service</i>. Thanks!   
    ]]>
</string>

Autolinking URLs——android:autolink

<TextView
     android:id="@+id/custom_font"
     android:layout_width="match_parent"
     android:layout_height="wrap_content"
     android:autoLink="all"
     android:linksClickable="true"
/>
text-autolink.png

与ListView的setOnItemClickListener响应事件冲突

在你的行布局中的根视图添加android:descendantFocusability ="blocksDescendants"

在TextView中显示图像

TextView支持将图像显示为其内容区域的一部分。 存储在“drawable”文件夹中的任何图像实际上可以嵌入到TextView中与文本相关的位置,使用android:drawableRightandroid:drawablePadding属性。 例如:

<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"     
    android:gravity="center"
    android:text="@string/my_contacts"
    android:drawableRight="@drawable/ic_action_add_group"
    android:drawablePadding="8dp"
/>

setCompoundDrawables()和setCompoundDrawablesWithIntrinsicBounds()

setCompoundDrawables()使用自己设置的drawable的边界

static public Drawable scaleDrawable(Drawable drawable, int width, int 
height) 
{ 
      int wi = drawable.getIntrinsicWidth(); 
      int hi = drawable.getIntrinsicHeight(); 
      int dimDiff = Math.abs(wi - width) - Math.abs(hi - height); 
      float scale = (dimDiff > 0) ? width/(float)wi : height/ 
(float)hi; 
      Rect bounds = new Rect(0, 0, (int)(scale*wi), (int)(scale*hi)); 
      drawable.setBounds(bounds); 
      return drawable; 
} 

使用自定义字体

字体存储在"assets"文件将中。下载任何字体,并将TTF文件放在 assets/fonts 目录中:

text-fonts.png
// Get access to our TextView
TextView txt = (TextView) findViewById(R.id.custom_font);
// Create the TypeFace from the TTF asset
Typeface font = Typeface.createFromAsset(getAssets(), "fonts/Chantelli_Antiqua.ttf");
// Assign the typeface to the view
txt.setTypeface(font);

也可以使用第三方库 calligraphy library

使用Spans

使用Spans对TextView中的文本部分应用样式,可以更改文本颜色,更改字体,添加下划线等,例如:

String firstWord = "Hello";
String secondWord = "World!";

TextView tvHelloWorld = (TextView)findViewById(R.id.tvHelloWorld);

// Create a span that will make the text red
ForegroundColorSpan redForegroundColorSpan = new ForegroundColorSpan(
        getResources().getColor(android.R.color.holo_red_dark));

// Use a SpannableStringBuilder so that both the text and the spans are mutable
SpannableStringBuilder ssb = new SpannableStringBuilder(firstWord);

// Apply the color span
ssb.setSpan(
        redForegroundColorSpan,            // the span to add
        0,                                 // the start of the span (inclusive)
        ssb.length(),                      // the end of the span (exclusive)
        Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); // behavior when text is later inserted into the SpannableStringBuilder
                                           // SPAN_EXCLUSIVE_EXCLUSIVE means to not extend the span when additional
                                           // text is added in later

// Add a blank space
ssb.append(" ");

// Create a span that will strikethrough the text
StrikethroughSpan strikethroughSpan = new StrikethroughSpan();

// Add the secondWord and apply the strikethrough span to only the second word
ssb.append(secondWord);
ssb.setSpan(
        strikethroughSpan,
        ssb.length() - secondWord.length(),
        ssb.length(),
        Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);

// Set the TextView text and denote that it is Editable
// since it's a SpannableStringBuilder
tvHelloWorld.setText(ssb, TextView.BufferType.EDITABLE);
text-spans.png

注意

  • SpannableStringBuilder(上面使用)是处理可变spans和可变text时使用的。
  • SpannableString是处理可变spans,但不可变的text时使用的。
  • SpannedString是处理不可变spans和不可变text时使用的。

可点击的spans——PatternEditableBuilder

在某些情况下,我们可能希望TextView中的不同子字符串使用不同的样式,然后可以单击以触发操作。 例如:

// Set text within a `TextView`
TextView textView = (TextView) findViewById(R.id.textView);
textView.setText("Hey @sarah, where did @jim go? #lost");
// Style clickable spans based on pattern
new PatternEditableBuilder().
    addPattern(Pattern.compile("\\@(\\w+)"), Color.BLUE,
       new PatternEditableBuilder.SpannableClickedListener() {
            @Override
            public void onSpanClicked(String text) {
                Toast.makeText(MainActivity.this, "Clicked username: " + text,
                    Toast.LENGTH_SHORT).show();
            }
       }).into(textView);
![Uploading text-spans_973591.png . . .]
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容