2010-11-08 70 views
2

我看到有一个TextAppearanceSpan可用,但没有使用的例子。我只是想让文本变成粗体,并保持其他所有内容不变 - 是否可以通过编程方式实现这种更简单的方法?在Android小部件中以编程方式设置文本样式的方法?

+0

仅供参考,这是用于设置上的选项卡插件的标题。 – Eno 2010-11-08 16:02:00

回答

3

所有你需要的是建立在res /值的XML文件,并写入类似以下内容:

<?xml version="1.0" encoding="utf-8"?> 
<resources> 
    <style name="header"> 
     /** here goes the style */ 
    </style> 
</resources> 

然后,所有你需要的是通过产生R.style.header到TextAppearanceSpan构造。

+0

我的标签是TextView,所以我最终使用Spannable类来应用样式。 – Eno 2010-11-11 14:58:41

2

它被记录在 http://developer.android.com/guide/appendix/faq/commontasks.html#selectingtext ,看看第二种方式使用Spannable

具体地说

// Get our EditText object. 
EditText vw = (EditText)findViewById(R.id.text); // or new etc 

// Set the EditText's text. 
vw.setText("Italic, highlighted, bold."); 

// Get the EditText's internal text storage 
Spannable str = vw.getText(); 

// Create our span sections, and assign a format to each. 
str.setSpan(new StyleSpan(android.graphics.Typeface.ITALIC), 0, 7, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); 
str.setSpan(new BackgroundColorSpan(0xFFFFFF00), 8, 19, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); 
str.setSpan(new StyleSpan(android.graphics.Typeface.BOLD), 21, str.length() - 1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); 
相关问题