And*_*ack 6 html java android image
我的一个项目活动包括用string.xml编写的长文本,我在textview中添加一些来自资源的图像,因为每个短语后都有图像,然后是文本短语然后是图像,依此类推,
我使用以下代码从字符串中获取图像:
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView htmlTextView = (TextView) findViewById(R.id.day_tv);
htmlTextView.setText(Html.fromHtml(getString(R.string.day), new ImageGetter(), null));
}
private class ImageGetter implements Html.ImageGetter {
public Drawable getDrawable(String source) {
int id = 0;
if (source.equals("image1.jpg")) {
id = R.drawable.a;
} else if (source.equals("image2.jpg")) {
id = R.drawable.b;
} else if (source.equals("image3.jpg")) {
id = R.drawable.c;
} else if (source.equals("image4.jpg")) {
id = R.drawable.d;
} else if (source.equals("image5.jpg")) {
id = R.drawable.e;
}
Drawable d = getResources().getDrawable(id);
d.setBounds(0, 0, d.getIntrinsicWidth(), d.getIntrinsicHeight());
return d;
}
};
}
Run Code Online (Sandbox Code Playgroud)
并在string.xml中编写html img标记:
<img src="image1.jpg">
Run Code Online (Sandbox Code Playgroud)
我希望能够通过更改其宽度和高度来自定义每个图像,或者将其引用为可绘制样式以在图像周围添加边框.
我尝试使用改变宽度和高度的波纹管代码:
<img src="image1.jpg" width="100" height="150">
Run Code Online (Sandbox Code Playgroud)
但它不起作用.
任何建议实现这一点将不胜感激,谢谢.
问题来自于Html.fromHtml()
,它只支持非常有限的标签和属性集。<img>
支持,但不支持设置图像的宽度和高度。可以使用 a TextView
(通过使用SpannableString
and ImageSpan
)来实现,但它更复杂并且不太灵活。
相反,您应该使用WebView
正确处理 HTML 的 。
加载字符串很容易:
WebView webView = (WebView) findViewById(R.id.web_view);
webView.loadData(getResources(R.string.day), "text/html", null);
Run Code Online (Sandbox Code Playgroud)
您可以在文档中找到更多示例。
只是为了比较,这里是一个不使用 的示例WebView
:
protected void onCreate(Bundle savedInstanceState) {
...
TextView textView = (TextView) findViewById(R.id.text_view);
SpannableString ss = new SpannableString("Hello :)");
// Draw the image with a size of 50x50
Drawable d = getResources().getDrawable(R.drawable.happy_face);
d.setBounds(0, 0, 50, 50);
// Replace the ":)" in the string by our drawable
ImageSpan span = new ImageSpan(d, ImageSpan.ALIGN_BASELINE);
ss.setSpan(span, 6, 8, Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
textView.setText(ss);
}
Run Code Online (Sandbox Code Playgroud)
它的加载速度会快得多,但您不能使用 HTML。