WebView:如何跨会话保留用户的缩放设置?

时间:2010-06-02 17:00:30

标签: android webview

我的应用程序使用WebView,用户有时会调整缩放级别以使文本更大。但是,当“活动”关闭且另一个活动开始时,缩放级别设置将丢失。

我无法看到如何在WebView上以编程方式获取和设置缩放级别,有人可以建议这样做吗?

3 个答案:

答案 0 :(得分:6)

我是来自Grupo Reforma的Jorge,这是我使用SharedPreferences的实现..

static final  String PREFS_Zoom = "PREFS_Zoom";

 private String zoomlevel;
 private int Default_zoomlevel=100;

     @Override
     public void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.main);

      mWebView = (WebView) findViewById(R.id.webview);        

      GetZoom();
      mWebView.setInitialScale(Default_zoomlevel);

      FrameLayout mContentView = (FrameLayout) getWindow().getDecorView().findViewById(android.R.id.content);
      View zoom = mWebView.getZoomControls();
      mContentView.addView(zoom, ZOOM_PARAMS);
      zoom.setVisibility(View.VISIBLE);

      WebSettings webSettings = mWebView.getSettings();
      webSettings.setSavePassword(false);
      webSettings.setSaveFormData(false);
      webSettings.setJavaScriptEnabled(true);
      webSettings.setSupportZoom(true);

      mWebView.loadUrl("http://www.elnorte.com");
    }



     private void GetZoom(){
      try{
       SharedPreferences settings = getSharedPreferences(PREFS_Zoom,0);
          zoomlevel = settings.getString("zoom_level","");     
       if (zoomlevel.length() >0)   
        Default_zoomlevel = Integer.parseInt(zoomlevel);               
       else
       Default_zoomlevel =100;
      }catch(Exception ex){
       Log.e("******ZOOM ! ", "Exception GetZoom()  ::"+ex.getMessage());          
      }
     }


     private void SaveZoom(){
      try{
       SharedPreferences settings = getSharedPreferences(PREFS_Zoom,0);            
       SharedPreferences.Editor editor = settings.edit();    
       Default_zoomlevel = (int) (mWebView.getScale() *100);
       editor.putString("zoom_level",""+ Default_zoomlevel);   
       editor.commit();
      }catch(Exception ex){
       Log.e("******ZOOM ! ", "Exception SaveZoom()  ::"+ex.getMessage());    
      }
     }


     public void finish() {  
      SaveZoom();
          super.finish();     
     }

我希望这个帮助

答案 1 :(得分:2)

Jorge给出的答案很明显,除了理想情况下不应该在finish()上调用SaveZoom(这是活动被销毁的时候)。更好的缩放偏好保存方法是扩展WebView的WebViewClient,并覆盖onScaleChanged()。继续Jorge的onCreate方法:

public void onCreate(Bundle savedInstanceState)
{

    ....

    class MyWebViewClient extends WebViewClient
    {
        @Override
        public void onScaleChanged(WebView wv, float oldScale, float newScale)
        {
            SaveZoom();
        }
    }

    mWebView.setWebViewClient(new MyWebViewClient());
}

答案 2 :(得分:1)