如何在安卓中以编程方式防止在 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