[英]Android html.fromHtml not working
我正在嘗試使用Html.fromHtml()在TextView中添加一些文本和圖像,但是它不起作用。
從資源獲取字符串並調用Html.fromHtml():
String insertedText = "<img src=\"small_image\"/>";
String strText = getResources().getString(R.string.big_string, insertedText);
myTextView.setText(Html.fromHtml(strText, context, null));
上下文是一項同時實現ImageGetter的活動。 這是getDrawable函數:
public Drawable getDrawable(String source) {
int id = 0;
Drawable drawable = null;
if(source.equals("small_image")){
id = R.drawable.small_image;
}
if (id > 0) {
drawable = getResources().getDrawable(id);
drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight());
}
return drawable;
}
在values.strings.xml文件中,我有:
<string name="big_string">"Big String %1$s"</string>
我在drawable文件夾中有small_image.png,在調試時,我可以看到id獲得正確的值,然后將位圖加載到drawable變量中,但它仍然渲染帶有'obj'的矩形。
知道為什么這樣做嗎?
我還嘗試使用SpannableStringBuilder並添加了一個圖像范圍,該范圍將替換文本中的“空格”,但這也不起作用。
我發現我的代碼有問題。 我在問題中寫的所有內容都是正確的,您可以將其用作在TextViews中合並圖像的參考。
問題是我正在使用屬性:
android:textAllCaps="true"
在xml文件中,以某種方式阻止了圖像的顯示。
String name = modelDispatchReportList.get(position).getName(); //get name from model class typed List
String text = "<font color='#000000'>" + name + "</font>"; //change color of name
/* check version of API to call method of Html class because fromHtml method is deprecated
* */
if (android.os.Build.VERSION.SDK_INT <= android.os.Build.VERSION_CODES.N) {
Log.d(TAG, "onBindViewHolder: if");
holder.textViewName.setText("12345" + " "); //set text to textView
holder.textViewName.append(Html.fromHtml(text)); //append text to textView
} else {
Log.d(TAG, "onBindViewHolder: else");
holder.textViewName.setText("12345" + " "); //set text to textView
holder.textViewName.append(Html.fromHtml(text, 0)); ////append text to textView
}
好吧,我嘗試了您的代碼,它正在工作...
順便說一句,我用了聾啞的ic_lancher drawable ...
我只是將textview設置為setContentView
。
我猜是textview的布局或drawable的問題嗎?
你能告訴我更多嗎?
只需將Textview
更改為WebView
並將內容設置為WebView
您不能通過html在textview上設置圖像。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.