我是一个新手,正在学习 Android 应用程序开发。
我已经开发了一个应用程序,它使用 WebView
加载网站链接,并且它正常工作。
但是当 WebView
加载页面时,我遇到了显示和隐藏进度条的问题。
我希望在 WebView
加载网站的主链接和内部链接时显示一个进度条(仅中心旋转),并在页面完全加载后隐藏进度条。
我的 Java 代码:
package in.matebook.myapplication;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
WebView myWebView = (WebView) findViewById(R.id.webView);
myWebView.setWebViewClient(new MyWebViewClient());
WebSettings webSettings = myWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
myWebView.loadUrl("http://www.labnol.org");
}
private class MyWebViewClient extends WebViewClient {
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if (Uri.parse(url).getHost().equals("www.labnol.org")) {
// This is my web site, so do not override; let my WebView load the page
//or we can add more allowed host in if condition
return false;
}
// Otherwise, the link is not for a page on my site, so launch another Activity that handles URLs
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
startActivity(intent);
return true;
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return false;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
我的布局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">
<WebView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/webView"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
/>
<ProgressBar
android:id="@+id/progressBar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
style="?android:attr/progressBarStyleLarge"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true" />
</RelativeLayout>
现在进度条已显示,但不会隐藏。
当我在Java代码中创建progressbar对象并添加以下行时,进度条不会显示。
progressbar.setVisibility(View.GONE);
我也尝试过另一个答案,但是当我点击内部链接时,进度条不起作用。
我想在主页面加载时显示进度条,并在主页面完全加载后隐藏进度条。
当用户点击网站的内部链接时,我想再次显示进度条,并在页面完全加载后隐藏进度条,与上述相同。
请帮助我,我是Android应用程序开发的初学者。