如何在安卓中以程式設計方式防止在 webView 中滾動?
本示例演示如何在安卓中以程式設計方式防止在 webView 中滾動。
步驟 1 − 在安卓工作室中建立一個新專案,進入檔案 ⇒ 新專案,填寫所有必需的詳細資訊以建立一個新專案。
步驟 2 − 新增以下程式碼到 res/layout/activity_main.xml 中。
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <ScrollView android:layout_width="wrap_content" android:layout_height="wrap_content" android:scrollbars="vertical"> </ScrollView> <WebView android:id="@+id/webView" android:layout_width="match_parent" android:layout_height="match_parent" /> </RelativeLayout>
步驟 3 − 新增以下程式碼到 src/MainActivity.java 中
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
public class MainActivity extends AppCompatActivity {
private WebView webView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
webView = findViewById(R.id.webView);
webView.setWebViewClient(new WebViewClient());
webView.loadUrl("https://www.youtube.com");
WebSettings webSettings = webView.getSettings();
webSettings.setJavaScriptEnabled(true);
webView.setOnTouchListener(new View.OnTouchListener(){
@Override
public boolean onTouch(View v, MotionEvent event){
return (event.getAction() == MotionEvent.ACTION_MOVE);
}
});
}
@Override
public void onBackPressed() {
if (webView.canGoBack()) {
webView.goBack();
} else {
super.onBackPressed();
}
}
}步驟 4 − 新增以下程式碼到 androidManifest.xml 中
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="app.com.sample"> <uses-permission android:name="android.permission.INTERNET" /> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/AppTheme"> <activity android:name=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest>
讓我們嘗試執行你的應用程式。我假設你已經將你的實際安卓移動裝置與你的計算機連線。要從安卓工作室執行該應用,開啟你的一個專案的活動檔案,然後點選工具欄中的執行
圖示。將你的移動裝置作為選項,然後檢查你的移動裝置,它會顯示你的預設螢幕 −

點選此處下載專案程式碼。
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP