2013-11-26 50 views
0

我試圖將圖像添加到WebView,然後滾動到圖像中心。但是computeHorizontalScrollRange()computeVeticalScrollRange()一直返回0。android在webview中居中圖像

web = (MyWebView)findViewById(R.id.webView); 
    web.setVerticalScrollBarEnabled(false); 
    web.setHorizontalScrollBarEnabled(false); 

    ImageView image = new ImageView(this); 
    image.setImageResource(R.drawable.image); 

    RelativeLayout.LayoutParams imageParams = 
      new RelativeLayout.LayoutParams 
      (RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT); 
    imageParams.height = 500; 
    imageParams.width = 500; 
    image.setLayoutParams(imageParams); 
    image.setScaleType(ScaleType.FIT_XY); 
    web.addView(image); 
    web.getViewTreeObserver().addOnGlobalLayoutListener(new OnGlobalLayoutListener() { 

     @Override 
     public void onGlobalLayout() { 
      // TODO Auto-generated method stub 
      web.getViewTreeObserver().removeGlobalOnLayoutListener(this); 
      web.scrollToCenter(); 
     } 
    }); 

而在擴展web視圖類:

public void scrollToCenter(){ 
    int cHoriz = computeHorizontalScrollRange()/2; 
    int cVertic = computeVerticalScrollRange()/2; 
    scrollTo(cHoriz, cVertic); 
} 

回答

0

嘗試此..設置高度寬度後

imageParams .addRule(RelativeLayout.CENTER_IN_PARENT, RelativeLayout.TRUE); 
image.setLayoutParams(imageParams); 

imageParams .addRule(RelativeLayout.CENTER_HORIZONTAL, RelativeLayout.TRUE);  
imageParams .addRule(RelativeLayout.CENTER_VERTICAL, RelativeLayout.TRUE); 
image.setLayoutParams(imageParams);