2012-06-01 26 views
0

当涉及到Android中布局的性能时,我有一个问题需要决定要走哪条路线。我有一个相当庞大的布局,需要使用API​​中的文本填充。现在的问题是,标题必须在加粗。为了简化它看起来像这样。带有样式文本的Android布局性能

图片说明1: Lorem存有...
图片说明2: Lorem存有...
标题3: Lorem存有...
等。

依我之见我有2个选择。要么我去了2次做到这一点,像

 <LinearLayout 
      android:layout_width="match_parent" 
      android:layout_height="wrap_content" 
      android:orientation="horizontal" > 

      <TextView 
       android:layout_width="wrap_content" 
       android:layout_height="wrap_content" 
       android:text="Caption 1" 
       android:textStyle="bold" /> 

      <TextView 
       android:layout_width="wrap_content" 
       android:layout_height="wrap_content" 
       android:text="Lorem ipsum..." /> 

     </LinearLayout> 

或者我去一个TextView的,并使用

Html.fromHtml("<b>Caption 1</b> Lorem ipsum") 

我对性能上的两种方法想知道的任何人有任何数字。考虑到我必须展示的大视野,这将是很好的知道。感觉像选项2更好,但我没有任何证据,我真的没有时间对它们进行测试。

干杯!

编辑:我忘了提,我已经在API的一些控制,以及这样我就可以在API中嵌入HTML和在

"<b>Caption</b> Lorem ipsum...". 

从两个初始答案来判断的形式发回弦第一种方法是在窗外。

+0

您可以修改该API,但如果将来您希望它是斜体而不是粗体?然后你必须再次修改API。根据运行时收集的信息,如果某些响应需要与其他响应不同,那该怎么办?如果存在已知模式“Caption():”,那么我建议在代码中处理它会更安全和更清晰。 – kcoppock

回答

1

如果您确实在寻找更快的性能,我建议您使用SpannableStringBuilder而不是Html.fromHtml

Html.fromHtml实际上在其实现中使用了SpannableStringBuilder,但是,从HTML中获得的实际上还需要时间来实际解析您的html字符串(并且添加到此时您需要将文本包装在html标签中) SpannableStringBuilder

而且任何这些变种会比填充和维护自个XML

PS更快意见我甚至约SpannableStringBuilder一个小文章,让你开始:http://illusionsandroid.blogspot.com/2011/05/modifying-coloring-scaling-part-of-text.html

+0

是的,我也看过,但是API的所有变化的长度都不尽相同,因为我必须指定每个范围,所以我有点犹豫不决。编辑:我也有(一些)控制API,所以我可以让它发回正确形成的字符串与已经嵌入的HTML – Slim

0

我< 3正则表达式,所以我喜欢这样的方法:

String myCaption = "Caption 1: Lorem Ipsum..."; 
TextView tv = (TextView)findViewById(R.id.mytextview); 

//Set a Regex pattern to find instances of "Caption X:" 
//where X is any integer. 
Pattern pattern = Pattern.compile("Caption [0-9]+:"); 

//Get a matcher for the caption string and find the first instance 
Matcher matcher = pattern.matcher(myCaption); 
matcher.find(); 

//These are the start and ending indexes of the discovered pattern 
int startIndex = matcher.start(); 
int endIndex = matcher.end(); 

//Sets a BOLD span on the 
Spannable textSpan = new Spannable(myCaption); 
textSpan.setSpan(new StyleSpan(Typeface.BOLD), 
    startIndex, endIndex, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); 

//Set this Spannable as the TextView text 
tv.setText(textSpan); 

我没有测试过这一点,但这个想法应该得到即使这不起作用,因为它是逐字的。基本上,使用正则表达式来查找字符串的“Caption X:”部分,获取开始和结束索引,并在该特定部分文本上设置粗体跨度。