这个功能主要是利用 SpannableString来实现的。先来看看效果图:
具体步骤如下:
1.在res/values/styles.xml文件中定义两个显示文本的style,分别给TextView中的第一行和第二行使用。代码如下:
<style name="tv_style1">
<item name="android:textSize">45sp</item>
<item name="android:textColor">@color/tab_bg_green</item>
<item name="android:textStyle">bold</item>
</style>
<style name="tv_style2">
<item name="android:textSize">25sp</item>
<item name="android:textColor">@color/tab_text_gray</item>
<item name="android:textStyle">bold</item>
</style>
2.定义一个布局文件如下:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="vertical" >
<TextView
android:id="@+id/id_tv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="aaaa"
android:gravity="center"
android:textSize="30sp"
/>
</LinearLayout>
- MainActivity中实现:
public class TextviewActivity extends Activity {
private TextView mTextView;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.my_layout);
mTextView = (TextView) findViewById(R.id.id_tv);
String value = "您已成功订购\n倒计时5分钟后播放";
initText(value);
}
private void initText(String value) {
SpannableString ss = new SpannableString(value);
ss.setSpan(new TextAppearanceSpan(this, R.style.tv_style1), 0, 6,
Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
ss.setSpan(new TextAppearanceSpan(this, R.style.tv_style2), 6,
value.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
mTextView.setText(ss, TextView.BufferType.SPANNABLE);
}
}
其中value中的“\n”表示换行。
ss.setSpan(new TextAppearanceSpan(this, R.style.tv_style1), 0, 6,
Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);表示将从0到第六个字设置为我们之前定义的第一种style,即 R.style.tv_style1。
以下引用
那么Spanned.SPAN_EXCLUSIVE_EXCLUSIVE表示什么意思呢?
Spanned.SPAN_EXCLUSIVE_EXCLUSIVE,这是在 setSpan 时需要指定的 flag——–它是用来标识在 Span 范围内的文本前后输入新的字符时是否把它们也应用这个效果。分别有 :
Spanned.SPAN_EXCLUSIVE_EXCLUSIVE(前后都不包括)、
Spanned.SPAN_INCLUSIVE_EXCLUSIVE(前面包括,后面不包括)、
Spanned.SPAN_EXCLUSIVE_INCLUSIVE(前面不包括,后面包括)、
Spanned.SPAN_INCLUSIVE_INCLUSIVE(前后都包括)。
效果如下: