android顯示html格式

Android中顯示html文件要用Html.fromHtml(...)處理過的返回值,返回值能夠成爲setText()的參數。php

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

public static Spanned fromHtml (String source)  

顯示帶圖片的html要用下面的方法處理html文件。android

public static Spanned fromHtml (String source, Html.ImageGetter p_w_picpathGetter, Html.TagHandler tagHandler)  

ImageGetter 爲處理html中<img>的處理器,生成Drawable對象並返回。 web

建立ImageGetter 主要實現下面的方法,source爲<img>標籤中src屬性的值。瀏覽器

public Drawable getDrawable(String source)  

下例爲在TextView和EditView中顯示html,並插入圖片。ide

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

 

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,p_w_picpathGetter,null));
         tv.setText(Html.fromHtml(ct,p_w_picpathGetter,null));
    }
    ImageGetter p_w_picpathGetter = 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()方法url

 

Uri uri = Uri.parse("http://www.baidu.com"); //要連接的地址spa

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

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.baidu.com");  

 

 

本文經兩篇合併而成

http://www.iteedu.com/handset/android/spannablediary/showhtmlp_w_picpath.php

http://hi.baidu.com/zp8126/item/e3b1b31c6e56597b7a5f2551

相關文章
相關標籤/搜索