2010-03-16 200 views
3

我是Android新手。Android:獲取WebView的滾動位置

我想簡單地知道用戶在頁面上滾動的位置。當網頁上的某個點出現在屏幕的底部時,我想觸發一個事件。但是這段代碼會導致異常。我知道WebView從View繼承getScrollY()。我沒有正確實施嗎?

在此先感謝。

public class Scroll extends Activity { 

    public WebView webview; 
    public float yPos; 

    @Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 

     WebView webview = new WebView(this); 
     setContentView(webview); 
     webview.loadUrl("file:///android_asset/Scroll.html"); 
    } 


    public boolean onTouchEvent(final MotionEvent event) { 
     if (event.getAction() == MotionEvent.ACTION_MOVE) { 
      yPos = webview.getScrollY(); 
      Log.v("Scroll", "yPos = " + yPos); 
     } 
     return false; 
    } 
} 

回答

2

而例外是?
這裏是的WebView屏幕高度一張紙條從我的應用程序之一:

// current position (top) = getScrollY(); 
// max position = getContentHeight(); 
// screen height = getHeight(); 
+1

感謝您的回答! 這是一個NullPointerException。 調試器停在行「yPos = webview.getScrollY()」,但我不知道空指針來自哪裏。 至於你的筆記,我使用getScrollY(),所以你已經確認這是正確的方法,但我使用它的方式顯然是錯誤的。 – Dave 2010-03-16 19:38:43

+0

事實上,我發現在「yPos = webview.getScrollY()」這行,「webview」變量爲null,即使在onCreate方法中,「WebView webview = new WebView(this);」工作中。 「webview」變量是否沒有擴展出onCreate方法的範圍?如果不是,我該如何處理它? – Dave 2010-03-16 19:43:28

+8

@Dave 它應該是webview = new WebView(this);而不是WebView webview =新的WebView(this);在onCreate(..)中。 – yanchenko 2010-03-16 22:38:52

3

你正在寫WebView webview;在onCreate()方法中兩個地方。

Aimply寫的 webview = new WebView(this);代替WebView webview = new WebView(this);

這樣就可以解決了空指針的問題。

0

的的WebView有一個方法,以獲取其內容的高度,這是我在我的解決方案中使用:

webView.setOnScrollChangeListener(new View.OnScrollChangeListener() { 
    @Override 
    public void onScrollChange(View view, int scrollX, int scrollY, int oldScrollX, int oldScrollY) { 
     WebView webView = (WebView) view; 
     float contentHeight = webView.getContentHeight() * webView.getScaleY(); 
     float total = contentHeight * getResources().getDisplayMetrics().density - view.getHeight(); 
     // on some devices just 1dp was missing to the bottom when scroll stopped, so we subtract it to reach 1 
     float percent = Math.min(scrollY/(total - getResources().getDisplayMetrics().density), 1); 
     Log.d("SCROLL", "Percentage: " + percent); 
     if (scrollY >= total - 1) { 
         Log.d("SCROLL", "Reached bottom"); 
     } 
    } 
} 

當心:

  • 的WebView規模必須加以考慮,以獲得總滾動高度
  • 顯示密度必須乘以內容高度才能將其與scrollY進行比較
  • 在我的Nexus 5X上安卓oid 8 scrollY從未到達高度,但在結束之前停止1dp(解決方法包含在代碼中)