我创建了一个小的Activity,它能够在webview中加载两个不同的HTML字符串。当我运行Activity时,它从page_1变量加载String开始。到现在为止还挺好。该页面按预期显示。 我添加了一个onFling监听器,它应该使活动加载page_2变量的内容。 问题是,即使调用onFling并调用loadUrl,webview也不会更新?
我的活动如下:
import android.app.Activity;
import android.os.Bundle;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.webkit.WebView;
public class Test extends Activity {
private GestureDetector mGestureDetector;
private WebView mWebView;
private int mPageIndex;
private static final String page_1 = "<html><body>Hello page 1</body></html>";
private static final String page_2 = "<html><body>Hello page 2</body></html>";
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.test);
mWebView = (WebView) findViewById(R.id.webview);
mWebView.loadData(page_1, "text/html", "utf-8");
setupGestureDetection();
mPageIndex = 0;
}
private void setupGestureDetection() {
mGestureDetector = new GestureDetector(new MyGestureDetector());
mWebView.setOnTouchListener(new OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
return mGestureDetector.onTouchEvent(event);
}
});
}
class MyGestureDetector extends GestureDetector.SimpleOnGestureListener {
private static final int SWIPE_DISTANCE_THRESHOLD = 120;
private static final int SWIPE_VELOCITY_THRESHOLD = 200;
private boolean isHorizontalSwipe(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
if (Math.abs(velocityX) > SWIPE_VELOCITY_THRESHOLD) {
if (Math.abs(e1.getX() - e2.getX()) > SWIPE_DISTANCE_THRESHOLD) {
return true;
}
}
return false;
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
if (isHorizontalSwipe(e1, e2, velocityX, velocityY)) {
if (e1.getX() > e2.getX()) {
// Right to left
if (++mPageIndex % 2 == 0) {
mWebView.loadData(page_1, "text/html", "utf-8");
} else {
mWebView.loadData(page_2, "text/html", "utf-8");
}
return true;
}
}
return false;
}
}
}
我的布局看起来像这样:
<?xml version="1.0" encoding="utf-8"?>
<WebView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/webview"
android:layout_width="fill_parent"
android:layout_height="fill_parent" />
我希望有一个人可以帮助我! :-)
最好的祝福
Stig Andersen