androidhtml图片
⑴ android中如何在textview中加入html
具体代码如下:
Android中的TextView,本身就支持部分的Html格式标签。这其中包括常用的字体大小颜色设置,文本链接等。使用起来也比较方便,只需要使用Html类转换一下即可。比如:
textView.setText(Html.fromHtml(str));
然而,有一种场合,默认支持的标签可能不够用。比如,我们需要在textView中点击某种链接,返回到应用中的某个界面,而不仅仅是网络连接,如何实现?
经过几个小时对android中的Html类源代码的研究,找到了解决办法,并且测试通过。
⑵ 如何在android中使用html作布局文件
在android开发中,通常使用xml格式来描述布局文件。就目前而言,熟悉android布局及美化的人员少之又少,出现了严重的断层。大部分企业,其实还是程序员自己动手布局。这样既浪费时间和精力,也未必能达到理想的效果。但是,在企业级的android开发中,使用html页面进行布局,也有很多的优势(例如:简单,大部分开发人员及美工都熟悉,方便统一进行更新,管理)。据笔者了解,已经有不少的公司在使用这种方式进行布局开发。这也可能是一种趋势。
下面,我将给出一个实例代码,供大家学习使用html页面给android应用布局。
java代码
package com.dazhuo.ui;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONObject;
import com.dazhuo.domain.Person;
import com.dazhuo.service.PersonService;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.webkit.WebView;
public class MainActivity extends Activity {
private PersonService service;
private WebView webview;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
service =new PersonService();
webview = (WebView) this.findViewById(R.id.webView);//android内置浏览器对象
webview.getSettings().setJavaScriptEnabled(true);//启用javascript支持
//添加一个js交互接口,方便html布局文件中的javascript代码能与后台java代码直接交互访问
webview.addJavascriptInterface(new PersonPlugin() , "Person");//new类名,交互访问时使用的别名
// <body onload="javascript:Person.getPersonList()">
webview.loadUrl("file:///android_asset/index.html");//加载本地的html布局文件
//其实可以把这个html布局文件放在公网中,这样方便随时更新维护 例如 webview.loadUrl("www.xxxx.com/index.html");
}
//定义一个内部类,从java后台(可能是从网络,文件或者sqllite数据库) 获取List集合数据,并转换成json字符串,调用前台js代码
private final class PersonPlugin{
public void getPersonList(){
List<Person> list = service.getPersonList();//获得List数据集合
//将List泛型集合的数据转换为JSON数据格式
try {
JSONArray arr =new JSONArray();
for(Person person :list)
{
JSONObject json =new JSONObject();
json.put("id", person.getId());
json.put("name", person.getName());
json.put("mobile",person.getMobile());
arr.put(json);
}
String JSONStr =arr.toString();//转换成json字符串
webview.loadUrl("javascript:show('"+ JSONStr +"')");//执行html布局文件中的javascript函数代码--
Log.i("MainActivity", JSONStr);
} catch (Exception e) {
// TODO: handle exception
}
}
//打电话的方法
public void call(String mobile){
Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:"+ mobile));
startActivity(intent);
}
}
}
Java代码
package com.dazhuo.domain;
public class Person {
private Integer id;
public Integer getId() {
return id;
}
public Person(Integer id, String name, String mobile) {
super();
this.id = id;
this.name = name;
this.mobile = mobile;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getMobile() {
return mobile;
}
public void setMobile(String mobile) {
this.mobile = mobile;
}
private String name;
private String mobile;
}
Java代码
package com.dazhuo.service;
import java.util.ArrayList;
import java.util.List;
import com.dazhuo.domain.Person;
public class PersonService {
public List<Person> getPersonList()
{
List<Person> list =new ArrayList<Person>();
list.add(new Person(32, "aa", "13675574545"));
list.add(new Person(32, "bb", "13698874545"));
list.add(new Person(32, "cc", "13644464545"));
list.add(new Person(32, "dd", "13908978877"));
list.add(new Person(32, "ee", "15908989898"));
return list;
}
}
Html代码
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<script type="text/javascript">
function show(jsondata){
var jsonobjs = eval(jsondata);
var table = document.getElementById("personTable");
for(var y=0; y<jsonobjs.length; y++){
var tr = table.insertRow(table.rows.length); //添加一行
//添加三列
var td1 = tr.insertCell(0);
var td2 = tr.insertCell(1);
td2.align = "center";
var td3 = tr.insertCell(2);
td3.align = "center";
//设置列内容和属性
td1.innerHTML = jsonobjs[y].id;
td2.innerHTML = jsonobjs[y].name;
td3.innerHTML = "<a href='javascript:Person.call(\""+ jsonobjs[y].mobile+ "\")'>"+ jsonobjs[y].mobile+ "</a>";
}
}
</script>
</head>
<!-- js代码通过webView调用其插件中的java代码 -->
<body onload="javascript:Person.getPersonList()">
<table border="0" width="100%" id="personTable" cellspacing="0">
<tr>
<td width="20%">编号</td><td width="40%" align="center">姓名</td><td align="center">电话</td>
</tr>
</table>
<a href="javascript:window.location.reload()">刷新</a>
</body>
</html>
⑶ android如何保存html文件,包括其中的图片。
1、先示例图片
2、操作代码
package com.nekocode.xue.utils;
import java.io.File;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import com.androidquery.AQuery;
import com.androidquery.callback.AjaxCallback;
import com.androidquery.callback.AjaxStatus;
import com.nekocode.xue.PublicData;
import com.nekocode.xue.PublicData.Subscribe;
public class HtmlStorageHelper {
private String URL = "http://eproject.sinaapp.com/fetchurl.php/getcontent/";
private PublicData pd;
private AQuery aq;
private SQLiteDatabase mDB;
private String mDownloadPath;
public HtmlStorageHelper(Context context) {
pd = PublicData.getInstance();
aq = new AQuery(context);
mDB = context.openOrCreateDatabase("data.db", Context.MODE_PRIVATE, null);
mDB.execSQL("create table if not exists download_html(_id INTEGER PRIMARY KEY AUTOINCREMENT, content_id TEXT NOT NULL, title TEXT NOT NULL)");
mDownloadPath = pd.mAppPath + "download/";
File dir_file = new File(pd.mAppPath + "download/");
if(!dir_file.exists())
dir_file.mkdir();
}
public void saveHtml(final String id, final String title) {
if(isHtmlSaved(id))
return;
aq.ajax(URL+id, String.class, new AjaxCallback<String>() {
@Override
public void callback(String url, String html, AjaxStatus status) {
File dir_file = new File(mDownloadPath + id);
if(!dir_file.exists())
dir_file.mkdir();
Pattern pattern = Pattern.compile("(?<=src=")[^"]+(?=")");
Matcher matcher = pattern.matcher(html);
StringBuffer sb = new StringBuffer();
while(matcher.find()){
downloadPic(id, matcher.group(0));
matcher.appendReplacement(sb, formatPath(matcher.group(0)));
}
matcher.appendTail(sb);
html = sb.toString();
writeHtml(id, title, html);
}
});
}
private void downloadPic(String id, String url) {
File pic_file = new File(mDownloadPath + id + "/" + formatPath(url));
aq.download(url, pic_file, new AjaxCallback<File>() {
@Override
public void callback(String url, final File file, AjaxStatus status) {
}
});
}
private void writeHtml(String id, String title, String html) {
File html_file = new File(mDownloadPath + id + "/index.html");
FileOutputStream fos = null;
try {
fos=new FileOutputStream(html_file);
fos.write(html.getBytes());
} catch (Exception e) {
e.printStackTrace();
}finally{
try {
fos.close();
} catch (Exception e2) {
e2.printStackTrace();
}
}
ContentValues values = new ContentValues();
values.put("content_id", id);
values.put("title", title);
mDB.insert("download_html", "_id", values);
}
public boolean isHtmlSaved(String id) {
File file = new File(mDownloadPath + id);
if(file.exists()) {
file = new File(mDownloadPath + id + "/index.html");
if(file.exists())
return true;
}
deleteHtml(id);
return false;
}
public String getTitle(String id) {
Cursor c = mDB.rawQuery("select * from download_html where content_id=?", new String[]{id});
if(c.getCount() == 0)
return null;
c.moveToFirst();
int index1 = c.getColumnIndex("title");
return c.getString(index1);
}
public ArrayList<Subscribe> getHtmlList() {
Cursor c = mDB.rawQuery("select * from download_html", null);
ArrayList<Subscribe> list = new ArrayList<Subscribe>();
if(c.getCount() != 0) {
c.moveToFirst();
int index1 = c.getColumnIndex("content_id");
int index2 = c.getColumnIndex("title");
while (!c.isAfterLast()) {
String id = c.getString(index1);
if(isHtmlSaved(id)) {
Subscribe sub = new Subscribe(
id,
c.getString(index2),
Subscribe.FILE_DOWNLOADED
);
list.add(sub);
}
c.moveToNext();
}
}
return list;
}
public void deleteHtml(String id) {
mDB.delete("download_html", "content_id=?", new String[]{id});
File dir_file = new File(mDownloadPath + id);
deleteFile(dir_file);
}
private void deleteFile(File file) {
if (file.exists()) { // 判断文件是否存在
if (file.isFile()) { // 判断是否是文件
file.delete(); // delete()方法 你应该知道 是删除的意思;
} else if (file.isDirectory()) { // 否则如果它是一个目录
File files[] = file.listFiles(); // 声明目录下所有的文件 files[];
for (int i = 0; i < files.length; i++) { // 遍历目录下所有的文件
this.deleteFile(files[i]); // 把每个文件 用这个方法进行迭代
}
}
file.delete();
} else {
//
}
}
private String formatPath(String path) {
if (path != null && path.length() > 0) {
path = path.replace("\", "_");
path = path.replace("/", "_");
path = path.replace(":", "_");
path = path.replace("*", "_");
path = path.replace("?", "_");
path = path.replace(""", "_");
path = path.replace("<", "_");
path = path.replace("|", "_");
path = path.replace(">", "_");
}
return path;
}
}
3、这段代码简单修改就可以用到自己的项目中了
⑷ Android开发中对显示HTML内容的几种方式
首先,Android中显示Html内容,有3中方式:(目前我用到的有这3种)
1、可以利用Android原生的Html.fromHtml(str, imageGetter, tagHandler)来进行显示。(不过,我这边用了,即使加了页面加载动画,还是觉得非常慢,有大量图片,会导致OOM;如果图片不多的话,可以考虑)
2、利用第三方插件HtmlTextView。
GitHub地址:https://github.com/PrivacyApps/html-textview
图片加载很顺畅,使用方法也非常简单,不过,有两个注意事项:
(1)其中,HtmlHttpImageGetter有3个构造函数,可以根据自己的情况选择。
(2)加载大量图片的时候,会导致OOM内存溢出。针对于这个情况,HtmlHttpImageGetter有一个压缩图片的方法可以调用,可以进去查看它的公共方法。(不过,我这边显示的图片过大,每张1M左右,并且一下子有几十张,即使设置了压缩图片,还是会导致OOM问题,目前还没解决,有大神知道咋弄的,拜托指点一下,非常感谢!)
对了,这个第三方插件的基本用法,点击上面的连接,进去一看就知道了,很简单。
3、第三种,是我没办法的情况下想的:把html标签里的内容利用正则表达式拿出来,其中,文本内容用一个TextView代替,<img>标签图片用一个ImageView代替,其他相关的标签自行选择替换。说白了,就是创建一个个的TextView以及ImageView填充到布局里(LinearLayout之类的)。要说明的是:其中图片显示用Glide来实现。目前我这边测试的情况还是可以的,加载的速度非常快,也没因内存问题导致APP崩溃。