getText 与getString的区别
1.从源码的注释中可以看出 getText返回了带有格式化信息的字串,getString返回了无格式化信息的字串
/**
* Return a localized, styled CharSequence from the application's package's
* default string table.
*
* @param resId Resource id for the CharSequence text
*/
@NonNull
public final CharSequence getText(@StringRes int resId) {
return getResources().getText(resId);
}
/**
* Returns a localized string from the application's package's
* default string table.
*
* @param resId Resource id for the string
* @return The string data associated with the resource, stripped of styled
* text information.
*/
@NonNull
public final String getString(@StringRes int resId) {
return getResources().getString(resId);
}
通过例子来看下实际的效果
//直接引用,跟进源码,使用了getText
TextView test = findViewById(R.id.test);
test.setText(R.string.cache_tips_message);
//getText 引用,带有格式信息,字串中的color生效
TextView test1 = findViewById(R.id.test1);
test1.setText(getText(R.string.cache_tips_message));
//getString 引用,不带有格式信息,字串中的color不生效
TextView test2 = findViewById(R.id.test2);
test2.setText(getString(R.string.cache_tips_message));
//fromHtml,因字串未带格式信息,失效
Spanned htmlString = Html.fromHtml(getString(R.string.cache_tips_message));
TextView test3 = findViewById(R.id.test3);
test3.setText(htmlString);
//使用CDATA包装,可以将字串中的全部信息保留下来,通过fromHtml解析,生效
Spanned htmlString1 = Html.fromHtml(getString(R.string.cache_tips_message1));
TextView test4 = findViewById(R.id.test4);
test4.setText(htmlString1);
//xml 中的字符串
<string name="cache_tips_message">当前缓存已达到<font color="#f55353">100MB</font>,建议您清理缓存,保证系统流畅!</string>
//使用cdata处理的字符串,CDATA全名为character data,指不使用XML解析器解析的文本数据。在标记CDATA下,所有与XML规范冲突的关键字字符串都被XML处理程序一视同仁地当做字符数据看待
<string name="cache_tips_message1"><![CDATA[当前缓存已达到<font color="#f55353">100MB</font>,建议您清理缓存,保证系统流畅]]></string>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:id="@+id/test"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<TextView
android:id="@+id/test1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<TextView
android:id="@+id/test2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<TextView
android:id="@+id/test3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<TextView
android:id="@+id/test4"
android:layout_width="wrap_content"
android:text="@string/cache_tips_message"
android:layout_height="wrap_content"/>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="check CurrentVision"
android:onClick="onCheckCurrentVision"/>
</LinearLayout>
实际效果
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-ZKM927DU-1575285776912)(D:\我的文档\11070535\Desktop\Screenshot_2019_1202_174157.png)]