webview使用及使用自定义图片查看界面

功能描述:业务需要,使用webview加载一个页面,在页面上的图片一点击时,能进行放大缩小等操作,如果我就使用webview加载页面,加载前判断如果是图片地址,则将图片URL作为参数传到自定义界面,在android界面就可以随意搞那处图片了:

1 主界面MainActivity代码:

package com.example.webviewtest;

import java.util.ArrayList;

import android.content.Intent;
import android.os.Bundle;
import android.view.KeyEvent;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ViewFlipper;

import com.example.webviewtest.utils.CLog;
import com.example.webviewtest.utils.Constant;

public class MainActivity  extends BaseActivity {

	private String TAG = "MainActivity";
	
	/**
	 * flipper主要是为了显示加载中,加载失败的状态而加入的东西
	 */
	private ViewFlipper flipper;
	
	/**
	 * 浏览器
	 */
	private WebView webview;
	
	private String mainUrl = "http://hz-chenwenbiao-91.iteye.com/blog/2038887";
//	private String mainUrl = "http://www.baidu.com";

	
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		this.setContentView(R.layout.activity_main);
		initialViews();
	}

	
	@Override
	public void initialViews() {

		
		flipper = (ViewFlipper) findViewById(R.id.class_space_detail_view_flipper);
		flipper.setDisplayedChild(0);
		
		/**
		 * 加载网页内容
		 */
		webview = (WebView) findViewById(R.id.class_space_detail_webview);
		// 设置WebView属性,能够执行Javascript脚本
		webview.getSettings().setJavaScriptEnabled(true);
		
		// 加载需要显示的网页
		CLog.d(TAG , "URL =========>" + mainUrl);
		webview.loadUrl(mainUrl);
		// 设置Web视图
		webview.setWebViewClient(new MyWebViewClient());
		
	}

	@Override
	// 设置回退
	// 覆盖Activity类的onKeyDown(int keyCoder,KeyEvent event)方法
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			
			if(webview.canGoBack()){
				webview.goBack(); // goBack()表示返回WebView的上一页面
			}
			else {
				finish();
			}
			return true;
		}
		return false;
	}
	
	

	// Web视图
	private class MyWebViewClient extends WebViewClient {
		@Override
		public boolean shouldOverrideUrlLoading(WebView view, String url) {
			
			CLog.d(TAG , "url ==========>" + url);
			
			
			if(url.contains(".png")){//我们根据访问的URL的特征,如果是图片文件,就使用自己的界面来加载,使用类IOS查看图片效果的photoview开源主组实现的
				//跳转到图片查看界面
				Intent intent = new Intent(MainActivity.this , ViewImageActivity.class);
				Bundle bundle = new Bundle();
				ArrayList<String> imageList = new ArrayList<String>();
				imageList.add(url);
				bundle.putStringArrayList(Constant.TAG_CLASS_IMAGE_URL , imageList);
	            bundle.putInt(Constant.TAG_CLASS_IMAGE_INDEX , 0);
	            intent.putExtras(bundle);
	            startActivity(intent);
				
                return true;
			}
			
			/**
			 * 使用webview方式加载页面
			 */
			view.loadUrl(url);
			
			return true;
		}
		
		
		
		@Override
		public void onPageFinished(WebView view, String url) {
			super.onPageFinished(view, url);
			flipper.setDisplayedChild(1);//完成显示网页内容
		}
				
	
		@Override
		public void onReceivedError(WebView view, int errorCode,
				String description, String failingUrl) {
			super.onReceivedError(view, errorCode, description, failingUrl);
			flipper.setDisplayedChild(2);//显示失败重新加载界面
		}
	}
	
	
}

2 主界面布局activity_main.xml:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical" >
    
    
    

    
    
    <ViewFlipper
    	android:id="@+id/class_space_detail_view_flipper"
	    android:orientation="vertical"
	    android:layout_width="fill_parent"
	    android:layout_height="fill_parent"
		android:background="@color/gray">		
		
        
        
		<!-- (0) ProgressBar -->
		<LinearLayout
		    android:id="@+id/class_space_detail_loading_layout"
		    android:layout_width="fill_parent"
		    android:layout_height="wrap_content"
		    android:layout_gravity="center_vertical"
		    android:gravity="center"
		    android:orientation="horizontal" >

		    <ProgressBar
		        android:id="@+id/class_space_detail_pb"
		        android:layout_width="42dp"
		        android:layout_height="42dp"
		        android:layout_marginRight="8dp"
		        android:indeterminateDrawable="@drawable/loading_rotate" >
		    </ProgressBar>

		    <TextView
		        android:id="@+id/ProgressTextView"
		        android:layout_width="wrap_content"
		        android:layout_height="wrap_content"
		        android:text="@string/loading"
		        android:textColor="#000"
		        android:textSize="16sp" >
		    </TextView>
		</LinearLayout>
		
		
		<!-- (1) webview -->	    
        <ScrollView
	        android:layout_width="fill_parent"
	        android:layout_height="fill_parent"
			android:background="@color/gray"
	        android:scrollbars="vertical" >
	
	        <WebView 
			    android:id="@+id/class_space_detail_webview"
			    android:layout_width="fill_parent"
			    android:layout_height="wrap_content"
			/>
	    </ScrollView>
        
       
		 <!-- (2) Retry button -->
        <RelativeLayout
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:padding="5dp"
            android:background="@drawable/get_data_failed" >

            <ImageView
                android:id="@+id/class_space_detail_retry_iv"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignParentBottom="true"
                android:layout_centerHorizontal="true"
                android:background="@drawable/selector_once_again" />
            
        </RelativeLayout>
		
    </ViewFlipper>
    
    
    

</RelativeLayout>

上面布局里加入了加载中,加载失败等状态的控件信息. 

3 自定义图片查看器界面ViewImageActivity.java:

/*******************************************************************************
 * Copyright 2011, 2012 Chris Banes.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *******************************************************************************/
package com.example.webviewtest;

import java.util.ArrayList;

import uk.co.senab.photoview.PhotoView;
import uk.co.senab.photoview.PhotoViewAttacher.OnPhotoTapListener;
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.example.webviewtest.utils.CLog;
import com.example.webviewtest.utils.Constant;
import com.example.webviewtest.utils.UniversalImageLoaderUtil;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.assist.ImageScaleType;


/**
 * 
 * 查看问题图片(使用开源代码)
 * 
 * @author chenwenbiao
 * @date 2013-10-29 上午11:08:15
 * @version V1.0
 */
public class ViewImageActivity extends Activity{

	private static String TAG = "ViewImageActivity";
	public Context mContext;
	
	/**
	 * 多张图片查看器
	 */
	private ViewPager mViewPager;

	/**
	 * 当前查看的是第几张图片
	 */
	private TextView mTextViewCurrentViewPosition;
	/**
	 * 图片的路径列表
	 */
	private static ArrayList<String> imagePathList = null;
	private static int currentViewPosition = 0;//当前浏览到哪一张图片
	private static PhotoView[] photoViewList = null;//记录放进viewPager的photoview,方便进行旋转
	private static int rotateRecord[] = null;//旋转角度记录
 	
	
	
	private static DisplayImageOptions options = null;
	private static ProgressBar spinner = null;
 
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.image_view);
		mContext = this;
		findViews();
		loadData();
		
		
		UniversalImageLoaderUtil.getInstance().setContext(this);//记得注册一下
	}

	private void loadData() {
		Bundle bundle = getIntent().getExtras();
		imagePathList = bundle.getStringArrayList(Constant.TAG_CLASS_IMAGE_URL);
		if(imagePathList == null){//图片路径都没有,就算了
			Toast.makeText(this, "image path list is null!", Toast.LENGTH_SHORT).show();
			finish();
			return;
		}
		
		
		options = new DisplayImageOptions.Builder()
		.showStubImage(R.drawable.uni_img_loading_shape)
		.showImageForEmptyUri(R.drawable.uni_img_loading_shape)
		.showImageOnFail(R.drawable.uni_img_loading_shape)
		.resetViewBeforeLoading(true)
		.cacheOnDisc(true)
//		.imageScaleType(ImageScaleType.EXACTLY)
		.imageScaleType(ImageScaleType.IN_SAMPLE_POWER_OF_2)
		.bitmapConfig(Bitmap.Config.RGB_565)
//		.displayer(new FadeInBitmapDisplayer(300))
		.build();
		
		
		
		
		currentViewPosition = bundle.getInt(Constant.TAG_CLASS_IMAGE_INDEX);
		mViewPager.setCurrentItem(currentViewPosition);//设置当前显示的pager
		
		if(imagePathList.size() == 1){//只有一张图片的浏览情况
			mTextViewCurrentViewPosition.setText("");
		}
		else {//多张图片的浏览情况
			mTextViewCurrentViewPosition.setText((currentViewPosition+1)+"/"+imagePathList.size());
		}
		
		
		CLog.d(TAG, "current view position:" + currentViewPosition);
		
		/**
		 * 初始化数组
		 */
		if(imagePathList != null && imagePathList.size() > 0){
			photoViewList = new PhotoView[imagePathList.size()];
			rotateRecord = new int[imagePathList.size()];
		}
		

		mViewPager.setAdapter(new SamplePagerAdapter());
	}
	
	public void findViews(){
		
		mViewPager = (ViewPager) findViewById(R.id.image_view_vp);//使用开源的图片浏览实现方式
		mTextViewCurrentViewPosition = (TextView) findViewById(R.id.image_which);
		
		
		//删除图片
		spinner = (ProgressBar) findViewById(R.id.loading);
		
		/**
		 * 设置这个,那么viewPager会将页面缓存起来,这里要注意,当设置过大时,可能会出现内存溢出
		 */
		mViewPager.setOffscreenPageLimit(4);
		
		/**
		 * 自己加一个页面变化的监听器,可以进页面的变化作相应的处理
		 */
		mViewPager.setOnPageChangeListener(new OnPageChangeListener() {
			
			@Override
			public void onPageSelected(int position) {//当前选择的是哪个图片
				// TODO Auto-generated method stub
				CLog.d(TAG, "currentViewPosition====>" + position);
				
				/**
				 * 更新当前图片浏览的位置
				 */
				currentViewPosition = position;
				
				mTextViewCurrentViewPosition.setText((currentViewPosition+1)+"/"+imagePathList.size());
			}
			
			@Override
			public void onPageScrolled(int arg0, float arg1, int arg2) {
				// TODO Auto-generated method stub
//				Log.d(TAG, "2");
			}
			
			@Override
			public void onPageScrollStateChanged(int arg0) {
				// TODO Auto-generated method stub
				CLog.d(TAG, "3====>" + arg0);
			}
			
		});
		
		
	};

	
	  private class SamplePagerAdapter extends PagerAdapter {
		@Override
		public int getCount() {
			if(imagePathList == null){
				return 0;
			}
			
			return imagePathList.size();
		}

		@Override
		public View instantiateItem(ViewGroup container, int position) {
			
			PhotoView photoView = new PhotoView(container.getContext());
			
			CLog.d(TAG, "picture path:" + imagePathList.get(currentViewPosition) + "\tposition:" + position);
			
			UniversalImageLoaderUtil.getInstance().display(imagePathList.get(position), photoView, options, spinner, null);

			photoView.setOnPhotoTapListener(new OnPhotoTapListener() {
				@Override
				public void onPhotoTap(View arg0, float arg1, float arg2) {
					((Activity)mContext).finish();
				}
			});
			container.addView(photoView, LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
			return photoView;
		}

		@Override
		public void destroyItem(ViewGroup container, int position, Object object) {
			container.removeView((View) object);
		}

		@Override
		public boolean isViewFromObject(View view, Object object) {
			return view == object;
		}

	}
	

}

4 自定义图片查看器布局image_view.xml:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical" >

    <com.example.webviewtest.view.HackyViewPager
        android:id="@+id/image_view_vp"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:gravity="center_vertical" >
    </com.example.webviewtest.view.HackyViewPager>

    <ProgressBar
        android:id="@+id/loading"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:layout_gravity="center"
        android:visibility="gone" />

    
    <TextView
        android:id="@+id/image_which"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:gravity="center_horizontal"
        android:paddingBottom="10dip"
        android:text="1/3" />

</RelativeLayout>

效果图:

1加载中:

2 加载完,显示网页内容,内容为我一个博文http://hz-chenwenbiao-91.iteye.com/blog/2038887:

3 点击网页图片,android界面显示图片:

附件是源码.点击下载

猜你喜欢

转载自hz-chenwenbiao-91.iteye.com/blog/2039800