TextView显示Html(带有网络图片)

网路图片加载方法:

1 ImageGetter中判断图片是否已经加载过,如果本地已经存在直接从本地加载

2 图片本地不存在,开启线程加载图片,下载完毕后,重新调用ImageGetter加载图片

主要代码:

 1  TextView加载html

		htmlText4 = (TextView) findViewById( R.id.htmlText4);
		Spanned span = Html.fromHtml( htmlStr,imgGetter2,null );
		htmlText4.setText(span);

 2 ImageGetter 使用

	//加载网络图片
	ImageGetter imgGetter2 = new Html.ImageGetter() {
        @Override
        public Drawable getDrawable(String source) {//参数为image的src属性
        	Drawable drawable = null; 
			String photoPath = FileUtils.getPhotoImgPath();
			String fileName =  FileUtils.getFileName(source );
			File imageFile = new File(photoPath,fileName);
			
			if(imageFile.exists()){//本地存在直接加载本地图片
	             //获取本地文件返回Drawable
                drawable=Drawable.createFromPath( imageFile.getAbsolutePath());
                //设置图片边界
//                drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight());
                drawable.setBounds(0, 0, 500, 500);
                
			}else{//图片没有家再过,则重新加载图片
				loadImage(source);
			}
             return drawable;
        }
	};

3 开启线程加载图片 

	//加载图片
	private void loadImage(final String imageUrl){
		new Thread(){
			public void run() {
				Bitmap bitmap = ApiClient.getNetBitmap( imageUrl);	
				String photoPath = FileUtils.getPhotoImgPath();
				String fileName =  FileUtils.getFileName(imageUrl );
				try {
					ImageUtils.saveImageToSD(HtmlActivity.this, photoPath+"/"+fileName, bitmap, 100);
				} catch (IOException e) {
					e.printStackTrace();
				}
				handler.sendEmptyMessage(1);
			};
		}.start();
	}

4 图片加载后,重新调用ImageGetter

	//加载图片后显示html文字
	private Handler handler = new Handler(){
		public void handleMessage(android.os.Message msg) {
			Spanned span = Html.fromHtml( htmlStr,imgGetter2,null );
			htmlText4.setText(span);
		};
	};

  

5 图片保存到本地的路径 

	/**
	 * 得到图片临时存储路径
	 * @return
	 */
	public static  String getPhotoImgPath(){
		String savePath = "";
		// 判断是否挂载了SD卡
		String storageState = Environment
				.getExternalStorageState();
		if (storageState.equals(Environment.MEDIA_MOUNTED)) {
			savePath = Environment
					.getExternalStorageDirectory() 
					+ "/Test/Camera/";// 存放照片的文件夹
			File savedir = new File(savePath);
			if (!savedir.exists()) {
				savedir.mkdirs();
			}
		}
		return savePath;
	}

猜你喜欢

转载自username2.iteye.com/blog/2227318