码迷,mamicode.com
首页 > Web开发 > 详细

WebView中查看图片(多张图片滑动查看)

时间:2015-05-29 17:33:46      阅读:344      评论:0      收藏:0      [点我收藏+]

标签:

1.在WebView中存在图片,android 中的java代码调用webview里面的js脚本

// 启用javascript  
webView.getSettings().setJavaScriptEnabled(true); 

webView.setWebViewClient(new WebViewClient() {

            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                super.onPageStarted(view, url, favicon);
                if (getIntent().getBooleanExtra(EXTRA_SHOW_HUD, false)) {
                }
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                //从assets目录下加载js文件"act.js"
                injectScriptFile(view, "act.js");

            }

            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                if (url.startsWith("tel:")) {
                    Intent intent = new Intent(Intent.ACTION_DIAL,
                            Uri.parse(url));
                    startActivity(intent);
                    return true;
                }
                return false;
            }

            public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
                Toast.makeText(DocumentDetailsActivity.this, "Oh no! " + description, Toast.LENGTH_SHORT).show();
            }

//加载js文件的方法
private void injectScriptFile(WebView view, String scriptFile) { InputStream input; try { input = getAssets().open(scriptFile); byte[] buffer = new byte[input.available()]; input.read(buffer); input.close(); String encoded = Base64.encodeToString(buffer, Base64.NO_WRAP); view.loadUrl("javascript:(function() {" + "var parent = document.getElementsByTagName(‘head‘).item(0);" + "var script = document.createElement(‘script‘);" + "script.type = ‘text/javascript‘;" + // Tell the browser to BASE64-decode the string into // your script !!! "script.innerHTML = window.atob(‘" + encoded + "‘);" + "parent.appendChild(script)" + "})()"); } catch (IOException e) { e.printStackTrace(); } } });

 

2.对webview绑定javascriptInterface

webView.addJavascriptInterface(this, "nativeDelegate");

 

3.参数的传递,以及界面的跳转(图片显示)

@JavascriptInterface
    public void showImage(String src) {
        Log.d("string", src);
        try {    
            //数据解析
            JSONObject o = new JSONObject(src);
            Intent intent = new Intent(this, ImageViewerActivity.class);
            String url = o.getString("src");
            //遍历JSONArray数据,加入到ArrayList中,实现数据的转换
            JSONArray jsonArray = o.getJSONArray("images");
            ArrayList<String> arrayList = new ArrayList<String>();

            int index = 0;
            for (int i = 0; i < jsonArray.length(); i++) {
                arrayList.add(jsonArray.getString(i));
                //设置当前图片的参数
                if (url.equals(jsonArray.getString(i)) ){
                    index = i;
                }
            }
            intent.putExtra("index", index);
            intent.putStringArrayListExtra("urls", arrayList);
            startActivity(intent);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

 

4.点击某张图片的时候,需要把这个图片的参数传给一个图片查看器,图片查看器里会根据传递进来的参数去加载这张图片,那么其实图片查看器就是一个新的单独的Activity,这个Activity会包含一个ViewPager,用来管理多张图片的查看。

activity_image_viewer.xml

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

    <com.example.ImageViewPager
        android:id="@+id/pager"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@android:color/black" />

</FrameLayout> 

ImageViewPager.java

public class ImageViewPager extends ViewPager {

    public ImageViewPager(Context context) {
        super(context);
    }

    public ImageViewPager(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    @Override
    public boolean onInterceptTouchEvent(MotionEvent ev) {
        try {
            return super.onInterceptTouchEvent(ev);
        } catch (IllegalArgumentException e) {
            return false;
        } catch (ArrayIndexOutOfBoundsException e) {
            return false;
        }
    }
}


ImageViewActivity.java

/** 
 * 图片查看器 
 */
public class ImageViewerActivity extends FragmentActivity {

    private static final String STATE_POSITION = "STATE_POSITION";
    public static final String INDEX = "index";
    public static final String URLS = "urls";

    private ImageViewPager mPager;
    private int pagerPosition;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_image_viewer);

        pagerPosition = getIntent().getIntExtra(INDEX, 0);
        ArrayList<String> urlList = getIntent().getStringArrayListExtra(URLS);

        mPager = (ImageViewPager) findViewById(R.id.pager);
        ImagePagerAdapter mAdapter = new ImagePagerAdapter(
                getSupportFragmentManager(), urlList);
        mPager.setAdapter(mAdapter);

        mPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {

            @Override
            public void onPageScrollStateChanged(int arg0) {
            }

            @Override
            public void onPageScrolled(int arg0, float arg1, int arg2) {
            }

            @Override
            public void onPageSelected(int arg0) {
            }

        });
        if (savedInstanceState != null) {
            pagerPosition = savedInstanceState.getInt(STATE_POSITION);
        }

        mPager.setCurrentItem(pagerPosition);
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        outState.putInt(STATE_POSITION, mPager.getCurrentItem());
    }

    private class ImagePagerAdapter extends FragmentStatePagerAdapter {

        public ArrayList<String> fileList;

        public ImagePagerAdapter(FragmentManager fm, ArrayList<String> fileList) {
            super(fm);
            this.fileList = fileList;
        }

        @Override
        public int getCount() {
            return fileList == null ? 0 : fileList.size();
        }

        @Override
        public Fragment getItem(int position) {
            String url = fileList.get(position);
            return ImageDetailFragment.newInstance(url);
        }
    }
}

 

5.已知图片查看的界面是继承自FragmentActivity的,所以支持显示的界面必须需要Fragment来实现,那么就自定义个Frangment吧,用这个Fragment来从参数中获取图片资源,显示图片。

image_detail_fragment.xml

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@android:color/black" >

    <ImageView
        android:id="@+id/image"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:adjustViewBounds="true"
        android:contentDescription="@string/app_name"
        android:scaleType="centerCrop" />

</FrameLayout>

ImageDetailFragment.java

public class ImageDetailFragment extends Fragment {
    private String mImageUrl;
    private ImageView mImageView;
    private PhotoViewAttacher mAttacher;

    public static ImageDetailFragment newInstance(String imageUrl) {
        final ImageDetailFragment f = new ImageDetailFragment();

        final Bundle args = new Bundle();
        args.putString("url", imageUrl);
        f.setArguments(args);

        return f;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mImageUrl = getArguments() != null ? getArguments().getString("url")
                : null;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        final View v = inflater.inflate(R.layout.image_detail_fragment,
                container, false);
        mImageView = (ImageView) v.findViewById(R.id.image);
        mAttacher = new PhotoViewAttacher(mImageView);

        mAttacher.setOnPhotoTapListener(new PhotoViewAttacher.OnPhotoTapListener() {

            @Override
            public void onPhotoTap(View arg0, float arg1, float arg2) {
                getActivity().finish();
            }
        });

        return v;
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        if (mImageUrl != null) {
            UrlImageViewHelper.setUrlDrawable(mImageView, mImageUrl, new UrlImageViewCallback() {

                @Override
                public void onLoaded(ImageView arg0, Bitmap arg1, String arg2, boolean arg3) {
                    mAttacher = new PhotoViewAttacher(mImageView);
                }
            });
        }
    }
}

 

WebView中查看图片(多张图片滑动查看)

标签:

原文地址:http://www.cnblogs.com/aiyobucuoo/p/4538892.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!