Подтвердить что ты не робот

Android: загрузка/содержание WebView в центре

Я загрузил изображение с помощью WebView, но когда оно уменьшено, максимальное изображение помещается в левом верхнем углу моего устройства. В любом случае загружать изображение так, чтобы оно отображалось в центре?

Ура!

4b9b3361

Ответ 1

Вы можете использовать этот код для центрирования изображения в центре экрана в WebView:

  //first you will need to find the dimensions of the screen 
  float width;
  float height;
  float currentHeight;
  WebView mWebView;

  //this function will set the current height according to screen orientation
  @Override
  public void onConfigurationChanged(Configuration newConfig){
          if(newConfig.equals(Configuration.ORIENTATION_LANDSCAPE)){

                currentHeight=width; 
                loadImage();                 

         }if(newConfig.equals(Configuration.ORIENTATION_PORTRAIT)){

                currentHeight=height;
                loadImage();

        }
    } 


  //call this function and it will place the image at the center
  public void load and center the image on screen(){

    mWebView=(WebView)findViewById(R.id.webview);
    mWebView.getSettings().setJavaScriptEnabled(true);
    mWebView.getSettings().setBuiltInZoomControls(true);       
    mWebView.setBackgroundColor(0);

    DisplayMetrics displaymetrics = new DisplayMetrics();
    getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
    height = displaymetrics.heightPixels;
    width = displaymetrics.widthPixels;
    currentHeight=height             //assuming that the phone
                                     //is held in portrait mode initially

         loadImage();        
  }
  public void loadImage(){
       Bitmap BitmapOfMyImage=BitmapFactory.decodeResource(Environment.getExternalStorgeDirectory().getAbsolutePath()+"yourFolder/myImageName.jpg");  

       mWebView.loadDataWithBaseURL("file:///"+Environment.getExternalStorgeDirectory().getAbsolutePath()
                                    +"yourFolder/","<html><center>
                                    <img src=\"myImageName.jpg\" vspace="
                                    +(currentHeight/2-(BitmapOfMyImage.getHeight()/2))+">
                                     </html>","text/html","utf-8","");
     //This loads the image at the center of thee screen                    

   }

Я использовал центральный тег для центрирования изображения по вертикали, а затем использовал тег vspace, чтобы получить верхний край изображения. Теперь маржа рассчитывается по: screenVierticalHeight/2-ImageVerticalHeight/2

Надеюсь, что это поможет

Ответ 2

Я сделал это с помощью комбинации XML и кода. У меня есть мой GIF файл, хранящийся в папке активов.

Ниже приведен код макета XML:

<RelativeLayout 
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

<WebView
    android:id="@+id/webView"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_centerVertical="true" />

</RelativeLayout>

Ниже приведен код Java:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_webview);
    WebView webView = (WebView) findViewById(R.id.webView);
    webView.setWebViewClient(new WebViewController());
    webView.loadDataWithBaseURL("file:///android_asset/","<html><center><img src=\"animation.gif\"></html>","text/html","utf-8","");
}

private class WebViewController extends WebViewClient {
     @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            view.loadUrl(url);
            return true;
        }
}

Ответ 3

    mWebView.loadDataWithBaseURL("file:///"+Environment.getExternalStorgeDirectory().getAbsolutePath()+"yourFolder/","<html><center><img src=\"myImage.jpg\"></html>","text/html","utf-8","");

Здесь размещается изображение из SDCard в центре webView. Надеюсь, это поможет

Ответ 4

String html = "<html><head><style type='text/css'>html,body {margin: 0;padding: 0;width: 100%;height: 100%;}html {display: table;}body {display: table-cell;vertical-align: middle;text-align: center;}</style></head><body><p style=\"color:white\">+"you message"+</p></body></html>";

webView.loadData(html, "text/html; charset = UTF-8", null);

Таким образом, это загрузит ваш веб-просмотр с текстом в центре

Ответ 5

Попробуйте загрузить HTML файл, в который встроено изображение. Все макеты могут выполняться со стандартными стилями CSS.

Ответ 6

У меня была такая же проблема - центрирование по вертикали в webview. Это решение работает большую часть времени... возможно, это может помочь вам немного

                int pheight = picture.getHeight();
                int vheight = view.getHeight();

                float ratio = (float) vheight / (float) pheight;

                System.out.println("pheight: " + pheight + "px");
                System.out.println("vheight: " + vheight + "px");
                System.out.println("ratio: " + ratio + "px");

                if (ratio > 0.5)
                {
                    return;
                }

                int diff = pheight - vheight;
                int diff2 = (int) ((diff * ratio) / 4);

                if (pheight > vheight)
                {
                    // scroll to middle of webview

                    currentPhotoWebview.scrollTo(0, diff2);
                    System.out.println("scrolling webview by " + diff2 + "px");

                }

Ответ 7

Я знаю этот ответ немного поздно, но здесь вариант без javascript:

вы можете расширить WebView и использовать защищенные методы computeHorizontalScrollRange() и computeVerticalScrollRange(), чтобы получить представление о максимальном диапазоне прокрутки и на основе этого вычислить, где вы хотите scrollTo с computeHorizontalScrollRange()/2 - getWidth()/2 and аналогично для вертикали: computeVerticalScrollRange()/2 - getHeight()/2

Мой единственный совет - убедиться, что загрузка завершена до этого, я не проверял, работает ли это во время загрузки, но я не думаю, что это будет так, что веб-просмотр еще не будет иметь диапазон прокрутки правильно настроенный (поскольку содержимое все еще загружается)

см. Android-просмотр Android: обнаружение прокрутки, где я получил большую часть своей информации.

Ответ 8

Для меня это работа:

String path = Environment.getExternalStorageDirectory().getAbsolutePath() + "PICTURE FILE NAME";
File file = new File(path);
String html = "<style>img{height: 100%;max-width: 100%;}</style> <html><head></head><body><center><img src=\"" + imagePath + "\"></center></body></html>";
webView.getSettings().setDefaultZoom(ZoomDensity.FAR);
webView.getSettings().setBuiltInZoomControls(true);
webView.getSettings().setUseWideViewPort(true); 
webView.getSettings().setLoadWithOverviewMode(true);
webView.loadDataWithBaseURL( "" ,  html, "text/html", "UTF-8", "");