0

当谈到 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...". 

从最初的两个答案来看,第一种方法是不可能的。

4

2 回答 2

1

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

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

并且这些变体中的任何一个都将比从 xml 填充和维护视图更快

PS我什至有一篇小文章SpannableStringBuilder让你开始:http: //illusionsandroid.blogspot.com/2011/05/modifying-coloring-scaling-part-of-text.html

于 2012-06-01T15:06:02.757 回答
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:”部分,获取开始和结束索引,并在该特定文本部分设置粗体跨度。

于 2012-06-01T15:15:22.987 回答