歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Android中顯示html標簽或者帶圖片

Android中顯示html標簽或者帶圖片

日期:2017/3/1 10:15:39   编辑:Linux編程

Android中顯示html文件要用Html.fromHtml(...)處理過的返回值,返回值可以成為setText()的參數。

只顯示帶文本的html可以用下面的方法處理html文件。

public static Spanned fromHtml (String source)
顯示帶圖片的html要用下面的方法處理html文件。

public static Spanned fromHtml (String source, Html.ImageGetter imageGetter, Html.TagHandler tagHandler)
ImageGetter 為處理html中<img>的處理器,生成Drawable對象並返回。

創建ImageGetter 主要實現下面的方法,source為<img>標簽中src屬性的值。

public Drawable getDrawable(String source)
下例為在TextView和EditView中顯示html,並插入圖片。

下圖只顯示html文字,點擊按鈕會在TextView和EditView文本後添加圖片。

public class AndroidTest2Activity extends Activity {
/** Called when the activity is first created. */
TextView tv;
EditText et;
Button addPic;
String ct;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
et=(EditText) this.findViewById(R.id.editText1);

tv=(TextView) this.findViewById(R.id.tv);
ct="aaa<font color=\"red\">aaa</font>";
addPic=(Button) this.findViewById(R.id.AddPic);
addPic.setOnClickListener(new OnClickListener(){

@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
ct+="<img src=\""+R.drawable.icon+"\"/>";
refreshView();
}

});

refreshView();


}
private void refreshView(){
et.setText(Html.fromHtml(ct,imageGetter,null));
tv.setText(Html.fromHtml(ct,imageGetter,null));
}
ImageGetter imageGetter = new ImageGetter()
{
@Override
public Drawable getDrawable(String source)
{
int id = Integer.parseInt(source);
Drawable d = getResources().getDrawable(id);
d.setBounds(0, 0, d.getIntrinsicWidth(), d .getIntrinsicHeight());
return d;
}
};

}

1.跳轉到浏覽器直接訪問頁面,這段代碼是在Activity中拷貝來的,所以有startActivity()方法

Uri uri = Uri.parse("http://www.linuxidc.com"); //要鏈接的地址

Intent intent = new Intent(Intent.ACTION_VIEW, uri);

startActivity(intent);

2.使用TextView顯示HTML方法

TextView text1 = (TextView)findViewById(R.id.TextView02);

text1.setText(Html.fromHtml(“<font size='20'>網頁內容</font>”));

3.直接使用android中自帶的顯示網頁組件WebView

webview = (WebView) findViewById(R.id.WebView01);

webview.getSettings().setJavaScriptEnabled(true);

webview.loadUrl("http://www.linuxidc.com");

Copyright © Linux教程網 All Rights Reserved