1.添加支持库依赖项:在 build.gradle 文件中添加以下行以添加 SwipeRefreshLayout 支持库:
implementation 'androidx.swiperefreshlayout:swiperefreshlayout:1.1.0'
2.在布局文件中添加 SwipeRefreshLayout 和 WebView:
<?xml version="1.0" encoding="utf-8"?>
<androidx.swiperefreshlayout.widget.SwipeRefreshLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/swipe_refresh_layout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<WebView
android:id="@+id/webview"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</androidx.swiperefreshlayout.widget.SwipeRefreshLayout>
3.缺少必要的权限:如果您的应用程序需要访问 Internet 权限,请确保在 AndroidManifest.xml 文件中添加以下行:
<uses-permission android:name="android.permission.INTERNET" />
4.以下是一个完整的示例Activity代码
import androidx.appcompat.app.AppCompatActivity;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;
import android.os.Bundle;
import android.os.Handler;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
private WebView webView;
private SwipeRefreshLayout swipeRefreshLayout;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
webView = findViewById(R.id.webview);
swipeRefreshLayout = findViewById(R.id.swipe_refresh_layout);
// 检查 Internet 权限
if (!hasInternetPermission()) {
Toast.makeText(this, "请授予应用程序 Internet 权限", Toast.LENGTH_SHORT).show();
finish();
return;
}
// 配置 WebView
webView.getSettings().setJavaScriptEnabled(true);
webView.setWebViewClient(new WebViewClient() {
@Override
public void onPageFinished(WebView view, String url) {
swipeRefreshLayout.setRefreshing(false);
}
});
webView.loadUrl("https://www.example.com");
// 配置 SwipeRefreshLayout
swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
@Override
public void onRefresh() {
// 检查 WebView 是否为空
if (webView == null) {
swipeRefreshLayout.setRefreshing(false);
return;
}
// 在 UI 线程上执行 WebView 刷新
new Handler().post(new Runnable() {
@Override
public void run() {
webView.reload();
}
});
}
});
}
private boolean hasInternetPermission() {
return checkSelfPermission(android.Manifest.permission.INTERNET) == getPackageManager().PERMISSION_GRANTED;
}
@Override
public void onBackPressed() {
// 如果 WebView 可以返回,则返回上一页
if (webView.canGoBack()) {
webView.goBack();
return;
}
// 否则退出应用程序
super.onBackPressed();
}
}