仅在第一个片段中捕获图像

时间:2016-06-06 18:29:26

标签: android image android-fragments canvas

我有两个片段,我使用webview来显示一些网站。在这些网站中,有一些我想要共享和保存的图像,为此,我使用位图创建画布以将图像保存到localstorage。

但是图像只是在片段A中创建,如果我触发从片段B保存图像,片段A的加载图像将被保存而不是B。

示例: - 假设猴子的图像显示在片段A上,鲸鱼的图像显示在片段B上,我想保存鲸鱼图像,为此我在片段B中选择保存图像选项,而不是保存鲸鱼&# 39; s图片,猴子的图片保存在本地存储中。

请告诉我代码中的错误。我用我的全部精力找出错误但却徒劳无功。需要Gurus的帮助。

片段A:

public class TopRatedFragment extends Fragment {

private ProgressBar progress;
private Menu optionsMenu;
private VideoEnabledWebView myWebView;
private VideoEnabledWebChromeClient webChromeClient;
private static final String TAG = TopRatedFragment.class.getSimpleName();

public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {

    View rootView = inflater.inflate(R.layout.fragment_top_rated, container, false);

    String url = "https://images.google.com";
    //layout
    myWebView = (VideoEnabledWebView) rootView.findViewById(R.id.webViewTop);
    mSwipeRefreshLayout = (SwipeRefreshLayout) rootView.findViewById(R.id.swiperefresh);
    progress = (ProgressBar) rootView.findViewById(R.id.progressBar3);
    View nonVideoLayout = rootView.findViewById(R.id.nonVideoLayout);
    ViewGroup videoLayout = (ViewGroup)rootView.findViewById(R.id.videoLayout);
    View loadingView = getActivity().getLayoutInflater().inflate(R.layout.view_loading_video, null);


  //settings

    myWebView.getSettings().setJavaScriptEnabled(true);
    myWebView.getSettings().setBuiltInZoomControls(true);
    mSwipeRefreshLayout.setColorSchemeColors(Color.BLUE, Color.RED, Color.GREEN, Color.YELLOW);
    myWebView.getSettings().setUserAgentString("Mozilla/5.0 (Linux; U; Android 2.2; en-us; Nexus One Build/FRF91) AppleWebKit/533.1 (KHTML, like Gecko) Version/4.0 Mobile Safari/533.1");




    registerForContextMenu(myWebView);

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        WebView.enableSlowWholeDocumentDraw();
    }

    myWebView.loadUrl(url);
    setHasOptionsMenu(true);
            mSwipeRefreshLayout.setOnRefreshListener(
            new SwipeRefreshLayout.OnRefreshListener() {
                @Override
                public void onRefresh() {
                    TopRatedFragment.this.myWebView.reload();


                }

            }
    );

    webChromeClient = new VideoEnabledWebChromeClient(nonVideoLayout,   videoLayout, loadingView, myWebView)
    { public void onProgressChanged(WebView view, int newProgress) {

         progress.setProgress(newProgress);
         progress.setVisibility(View.VISIBLE);
          setRefreshActionButtonState(true);


          if (newProgress == 100) {
           progress.setVisibility(View.GONE);
           setRefreshActionButtonState(false);
              mSwipeRefreshLayout.setRefreshing(false);


             }
           }
         };
     myWebView.setWebChromeClient(webChromeClient);
    myWebView.setWebViewClient(new InsideWebViewClient());

    myWebView.setOnKeyListener(new View.OnKeyListener() {
        @Override
        public boolean onKey(View v, int keyCode, KeyEvent event) {
            if (event.getAction() == KeyEvent.ACTION_DOWN) {
                WebView webView = (WebView) v;

                switch (keyCode) {
                    case KeyEvent.KEYCODE_BACK:
                        if (webView.canGoBack()) {
                            webView.goBack();
                            return true;
                        }
                        break;
                }
            }

            return false;
        }
    });



    return rootView;

}
  private class InsideWebViewClient extends WebViewClient {
    @Override
    public boolean shouldOverrideUrlLoading(WebView View, String url){

        if( url.startsWith("https:") || url.startsWith("http:") ) {
            TopRatedFragment.this.progress.setProgress(0);
            View.loadUrl(url);
            return false;
        }
        Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
        startActivity( intent );
        return true;
    }
 }
  // Now comes the real problem.
  @Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo)
{
    super.onCreateContextMenu(menu, v, menuInfo);
     WebView w = (WebView)v;
    WebView.HitTestResult result = w.getHitTestResult();
       if(result.getType() == WebView.HitTestResult.IMAGE_TYPE || result.getType() == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE) {
           menu.addSubMenu(1, 1, 1, "Share image");
           strUrl = result.getExtra();

           menu.addSubMenu(0,0,0,"Save image");

       }
}
private void captureWV2() {


    myWebView.measure(View.MeasureSpec.makeMeasureSpec(
            View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED),
            View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
    myWebView.layout(0, 0, myWebView.getMeasuredWidth(),
            myWebView.getMeasuredHeight());
    myWebView.setDrawingCacheEnabled(true);
    myWebView.buildDrawingCache();
    Bitmap bm = Bitmap.createBitmap(myWebView.getMeasuredWidth(),
            myWebView.getMeasuredHeight(), Bitmap.Config.ARGB_8888);

    Canvas bigcanvas = new Canvas(bm);

    myWebView.draw(bigcanvas);
    System.out.println("1111111111111111111111="
            + bigcanvas.getWidth());
    System.out.println("22222222222222222222222="
            + bigcanvas.getHeight());

    if (bm != null) {
        String file_path = Environment.getExternalStorageDirectory().getAbsolutePath() +
                "/TempImages";
        File dir = new File(file_path);
        if(!dir.exists())
            dir.mkdirs();

        String format = new SimpleDateFormat("yyyyMMddHHmmss",
                java.util.Locale.getDefault()).format(new Date());

        File file = new File(dir, format + ".png");
        FileOutputStream fOut;
        try {
            fOut = new FileOutputStream(file);
            bm.compress(Bitmap.CompressFormat.PNG, 85, fOut);
            fOut.flush();
            fOut.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

        Uri uri = Uri.fromFile(file);
        Intent intent = new Intent(android.content.Intent.ACTION_SEND);
        intent.setType("image/*");
        intent.putExtra(Intent.EXTRA_STREAM, uri);

        startActivity(Intent.createChooser(intent,"Sharing something"));
        }
        }

  private void saveimage2() {

myWebView.measure(View.MeasureSpec.makeMeasureSpec(
        View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED),
        View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
myWebView.layout(0, 0, myWebView.getMeasuredWidth(),
        myWebView.getMeasuredHeight());
myWebView.setDrawingCacheEnabled(true);
myWebView.buildDrawingCache();
Bitmap bm = Bitmap.createBitmap(myWebView.getMeasuredWidth(),
        myWebView.getMeasuredHeight(), Bitmap.Config.ARGB_8888);

Canvas bigcanvas = new Canvas(bm);

myWebView.draw(bigcanvas);
System.out.println("1111111111111111111111="
        + bigcanvas.getWidth());
System.out.println("22222222222222222222222="
        + bigcanvas.getHeight());

if (bm != null) {
    String file_path = Environment.getExternalStorageDirectory().getAbsolutePath() +
            "/DCIM";
    File dir = new File(file_path);
    if (!dir.exists())
        dir.mkdirs();

    String format = new SimpleDateFormat("yyyyMMddHHmmss",
            java.util.Locale.getDefault()).format(new Date());

    File file = new File(dir, format + ".png");
    FileOutputStream fOut;
    try {
        fOut = new FileOutputStream(file);
        bm.compress(Bitmap.CompressFormat.PNG, 85, fOut);
        fOut.flush();
        fOut.close();
    } catch (Exception e) {
        e.printStackTrace();
    }

}
 }

@Override
public boolean onContextItemSelected(MenuItem item){
          if(item.getTitle()=="Share image") {
              captureWV2();
             }
    if (item.getTitle()=="Save image"){
        saveimage2();
    }

    return true;
  }

@Override
public void onCreateOptionsMenu(
        Menu menu, MenuInflater inflater) {
    this.optionsMenu = menu;
    inflater.inflate(R.menu.airport_menu, menu);

}

public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
        case R.id.airport_menuRefresh:
            setRefreshActionButtonState(true);
            TopRatedFragment.this.myWebView.reload();

            return true;

    }
    return super.onOptionsItemSelected(item);
}
public void setRefreshActionButtonState(final boolean refreshing) {
    if (optionsMenu != null) {
        final MenuItem refreshItem = optionsMenu
                .findItem(R.id.airport_menuRefresh);
        if (refreshItem != null) {
            if (refreshing) {
                refreshItem.setActionView(R.layout.actionbar_indeterminate_progress);
            } else {
                refreshItem.setActionView(null);
            }
        }
    }
}

 }

片段B:

public class MoviesFragment extends Fragment{

private ProgressBar progress;
private VideoEnabledWebView myWebView;
private VideoEnabledWebChromeClient webChromeClient;
private Menu optionsMenu;
private static final String TAG = MoviesFragment.class.getSimpleName();
public static final int INPUT_FILE_REQUEST_CODE = 1;
private ValueCallback<Uri> mUploadMessage;
private final static int FILECHOOSER_RESULTCODE=1;
private ValueCallback<Uri[]> mFilePathCallback;
private String mCameraPhotoPath;
private SwipeRefreshLayout mSwipeRefreshLayout;
private Uri mCapturedImageURI = null;
private String strUrl = "";
private boolean _hasLoadedOnce= false;
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {

    View rootView = inflater.inflate(R.layout.fragment_movies, container, false);
return rootView;
}

View myUIUpdate2(View view){


    //layout
    String url = "https://m.example.com";
    myWebView = (VideoEnabledWebView) view.findViewById(R.id.webViewMovies);
    mSwipeRefreshLayout = (SwipeRefreshLayout) view.findViewById(R.id.swiperefresh1);
    progress = (ProgressBar) view.findViewById(R.id.progressBar2);
    View nonVideoLayout = view.findViewById(R.id.nonVideoLayout1); // Your own view, read class comments
    ViewGroup videoLayout = (ViewGroup)view.findViewById(R.id.videoLayout1); // Your own view, read class comments
    View loadingView = getActivity().getLayoutInflater().inflate(R.layout.view_loading_video, null); // You
    //settings

    progress.setMax(100);
    registerForContextMenu(myWebView);

    myWebView.getSettings().setBuiltInZoomControls(true);
    myWebView.getSettings().setJavaScriptEnabled(true);
    mSwipeRefreshLayout.setColorSchemeColors(Color.BLUE, Color.RED, Color.GREEN, Color.YELLOW);
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        WebView.enableSlowWholeDocumentDraw();
    }
    setHasOptionsMenu(true);

    mSwipeRefreshLayout.setOnRefreshListener(
            new SwipeRefreshLayout.OnRefreshListener() {
                @Override
                public void onRefresh() {
                    MoviesFragment.this.myWebView.reload();


                }


            }
    );





    webChromeClient = new VideoEnabledWebChromeClient(nonVideoLayout, videoLayout, loadingView, myWebView) {
public void onProgressChanged(WebView view, int newProgress) {

                                         progress.setProgress(newProgress);
                                         progress.setVisibility(View.VISIBLE);
                                         setRefreshActionButtonState(true);
                                         if (newProgress == 100) {
                                             progress.setVisibility(View.GONE);
                                             setRefreshActionButtonState(false);
                                             mSwipeRefreshLayout.setRefreshing(false);
                                         }
                                     }


                                 };
myWebView.setWebChromeClient(webChromeClient);

    myWebView.setWebViewClient(new InsideWebViewClient());



    myWebView.setOnKeyListener(new View.OnKeyListener() {
        @Override
        public boolean onKey(View v, int keyCode, KeyEvent event) {
            if (event.getAction() == KeyEvent.ACTION_DOWN) {
                WebView webView = (WebView) v;

                switch (keyCode) {
                    case KeyEvent.KEYCODE_BACK:
                        if (webView.canGoBack()) {
                            webView.goBack();
                            return true;
                        }
                        break;
                }
            }

            return false;
        }
    });



    myWebView.loadUrl(url);
    return view;

}


@Override
public void setUserVisibleHint(boolean isFragmentVisible_) {
    super.setUserVisibleHint(true);


    if (this.isVisible()) {
        // we check that the fragment is becoming visible
        if (isFragmentVisible_ && !_hasLoadedOnce) {
            myUIUpdate2(getView());
            _hasLoadedOnce = true;
        }
    }
}
@Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo)
{
    super.onCreateContextMenu(menu, v, menuInfo);



    WebView w = (WebView)v;
    WebView.HitTestResult result = w.getHitTestResult();

    if(result.getType() == WebView.HitTestResult.IMAGE_TYPE || result.getType() == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE) {
        menu.addSubMenu(2, 1, 1, "Share image");
        strUrl = result.getExtra();

        menu.addSubMenu(1,0,0,"Save image");

    }
}
private void captureWV() {

    myWebView.measure(View.MeasureSpec.makeMeasureSpec(
            View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED),
            View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
    myWebView.layout(0, 0, myWebView.getMeasuredWidth(),
            myWebView.getMeasuredHeight());
    myWebView.setDrawingCacheEnabled(true);
    myWebView.buildDrawingCache();
    Bitmap bm1 = Bitmap.createBitmap(myWebView.getMeasuredWidth(),
            myWebView.getMeasuredHeight(), Bitmap.Config.ARGB_8888);

    Canvas bigcanvas = new Canvas(bm1);

    myWebView.draw(bigcanvas);
    System.out.println("1111111111111111111111="
            + bigcanvas.getWidth());
    System.out.println("22222222222222222222222="
            + bigcanvas.getHeight());

    if (bm1 != null) {
        String file_path = Environment.getExternalStorageDirectory().getAbsolutePath() +
                "/TempImages";
        File dir = new File(file_path);
        if(!dir.exists())
            dir.mkdirs();

        String format = new SimpleDateFormat("yyyyMMddHHmmss",
                java.util.Locale.getDefault()).format(new Date());

        File file = new File(dir, format + ".png");
        FileOutputStream fOut;
        try {
            fOut = new FileOutputStream(file);
            bm1.compress(Bitmap.CompressFormat.PNG, 85, fOut);
            fOut.flush();
            fOut.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

        Uri uri = Uri.fromFile(file);
        Intent intent = new Intent(android.content.Intent.ACTION_SEND);
        intent.setType("image/*");
        intent.putExtra(Intent.EXTRA_STREAM, uri);

        startActivity(Intent.createChooser(intent,"Sharing something"));
    }
}

private void saveimage() {

    myWebView.measure(View.MeasureSpec.makeMeasureSpec(
            View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED),
            View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
    myWebView.layout(0, 0, myWebView.getMeasuredWidth(),
            myWebView.getMeasuredHeight());
    myWebView.setDrawingCacheEnabled(true);
    myWebView.buildDrawingCache();
    Bitmap bm1 = Bitmap.createBitmap(myWebView.getMeasuredWidth(),
            myWebView.getMeasuredHeight(), Bitmap.Config.ARGB_8888);

    Canvas bigcanvas = new Canvas(bm1);

    myWebView.draw(bigcanvas);
    System.out.println("1111111111111111111111="
            + bigcanvas.getWidth());
    System.out.println("22222222222222222222222="
            + bigcanvas.getHeight());

    if (bm1 != null) {
        String file_path = Environment.getExternalStorageDirectory().getAbsolutePath() +
                "/DCIM";
        File dir = new File(file_path);
        if (!dir.exists())
            dir.mkdirs();

        String format = new SimpleDateFormat("yyyyMMddHHmmss",
                java.util.Locale.getDefault()).format(new Date());

        File file = new File(dir, format + ".png");
        FileOutputStream fOut;
        try {
            fOut = new FileOutputStream(file);
            bm1.compress(Bitmap.CompressFormat.PNG, 85, fOut);
            fOut.flush();
            fOut.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}

@Override
public boolean onContextItemSelected(MenuItem item){
    if(item.getTitle()=="Share image") {
        captureWV();
    }
    if (item.getTitle()=="Save image"){
        saveimage();
    }

    return true;
}

@Override
public void onCreateOptionsMenu(
        Menu menu, MenuInflater inflater) {
    this.optionsMenu = menu;
    inflater.inflate(R.menu.airport_menu, menu);

}

public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
        case R.id.airport_menuRefresh:
            setRefreshActionButtonState(true);
            MoviesFragment.this.myWebView.reload();
            return true;

    }
    return super.onOptionsItemSelected(item);
}



public void setRefreshActionButtonState(final boolean refreshing) {
    if (optionsMenu != null) {
        final MenuItem refreshItem = optionsMenu
                .findItem(R.id.airport_menuRefresh);
        if (refreshItem != null) {
            if (refreshing) {
                refreshItem.setActionView(R.layout.actionbar_indeterminate_progress);
            } else {
                refreshItem.setActionView(null);
            }
        }
    }
}

private class InsideWebViewClient extends WebViewClient {
    @Override
    public boolean shouldOverrideUrlLoading(WebView View, String url){
        if( url.startsWith("https:") || url.startsWith("http:") ) {
            MoviesFragment.this.progress.setProgress(0);
            View.loadUrl(url);
            return false;
        }
        Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
        startActivity( intent );
        return true;
    }
}
}

更新

如果我从片段A中删除共享意图,然后尝试从片段B共享图像,则片段B中的共享意图不会触发。

1 个答案:

答案 0 :(得分:0)

<强>解决

在创造了一些新的能量(违反物理定律)后,我发现,罪魁祸首是oncontextitemselectedoncontextitemselected负责分享片段中的意图,这就是为什么我得到了不同的图像。

并且oncontextitemselected只是从第一个片段调用,这是该问题的主要原因。但最后我解决了这个问题。

@Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo)
{
    super.onCreateContextMenu(menu, v, menuInfo);
    WebView w = (WebView)v;
    WebView.HitTestResult result = w.getHitTestResult();
    MenuItem.OnMenuItemClickListener handler = new MenuItem.OnMenuItemClickListener() {
        public boolean onMenuItemClick(MenuItem item) {

            if (item.getTitle() == "Share Image") {
                captureWV2();
            }
            if (item.getTitle() == "Save Image") {
                saveimage2();
            }
            return true;
        }
    };

    if(result.getType() == WebView.HitTestResult.IMAGE_TYPE || result.getType() == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE) {

        menu.add(0, ID_SHAREIMAGE, 0, "Share Image").setOnMenuItemClickListener(handler);
        menu.add(0, ID_SAVEIMAGE, 0, "Save Image").setOnMenuItemClickListener(handler);

    }
}