具有样式文本的Android布局性能

时间:2012-06-01 14:57:04

标签: android performance android-layout

我在确定Android的布局性能方面遇到了问题。我有一个庞大的布局,需要使用API​​中的文本填充。现在的问题是字幕必须是粗体。简化它看起来像这样。

标题1: Lorem ipsum ...
标题2: Lorem ipsum ...
标题3: Lorem ipsum ...
等。

在我看来,我有两个选择。我要么用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...". 

从两个初步答案来看,第一种方法已经过时了。

2 个答案:

答案 0 :(得分:1)

如果您真的想要更快的表现,我建议您使用SpannableStringBuilder代替Html.fromHtml

Html.fromHtml实际上在它的实现中使用了SpannableStringBuilder,但是给定,fromHtml也需要时间来实际解析你的html字符串(并添加到你需要在html标签中包装文本的时间)它会执行速度低于SpannableStringBuilder

任何这些变体都比从xmls填充和维护视图更快

P.S。我甚至有一篇关于SpannableStringBuilder的文章来帮助您入门:http://illusionsandroid.blogspot.com/2011/05/modifying-coloring-scaling-part-of-text.html

答案 1 :(得分:0)

我&lt; 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);

我没有测试过这个,但是这个想法应该让你去,即使这不是因为它是逐字的。基本上,使用Regex查找字符串的“Caption X:”部分,获取开始和结束索引,并在该特定文本部分设置Bold范围。