安卓-浏览器进度条

3
我已经在webview上方添加了进度条。 每当我点击一个链接时,我都会让进度条可见。
我希望进度条能覆盖在webview上,并且我想显示进度条的百分比。我知道CSS,但我不知道如何在安卓中更改进度条的位置。
<?xml version="1.0" encoding="utf-8"?>
<WebView  xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/webview01"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
/> 

MainActivity.java

public class MainActivity extends Activity {

WebView web;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    web = (WebView) findViewById(R.id.webview01);
 // request the progress-bar feature for the activity
    getWindow().requestFeature(Window.FEATURE_PROGRESS);

    // set a webChromeClient to track progress    
    web.setWebChromeClient(new WebChromeClient()
    {
        public void onProgressChanged(WebView view, int progress)
        {
            // update the progressBar
            MainActivity.this.setProgress(progress * 100);
        }
    });


    web.getSettings().setJavaScriptEnabled(true);
    web.loadUrl("url");

}

// To handle "Back" key press event for WebView to go back to previous screen.
@Override
public boolean onKeyDown(int keyCode, KeyEvent event)
{
    if ((keyCode == KeyEvent.KEYCODE_BACK) && web.canGoBack()) {
        web.goBack();
        return true;
    }
    return super.onKeyDown(keyCode, event);
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}

要显示进度条百分比,我需要修改这段代码吗?还是可以从这段代码中扩展功能?

1个回答

7
要显示“页面加载”进度条,请使用以下代码:
在onCreate()中:
// request the progress-bar feature for the activity
getWindow().requestFeature(Window.FEATURE_PROGRESS);

// set a webChromeClient to track progress    
myWebView.setWebChromeClient(new WebChromeClient()
{
 public void onProgressChanged(WebView view, int progress)
 {
   // update the progressBar
   MyActivity.this.setProgress(progress * 100);
 }
});

这将显示在屏幕顶部使用内置样式,就像内置浏览器一样。

如果您想要显示和更新自己的进度条,流程是类似的,需要获取到进度条的句柄:

ProgressBar myProgress = (ProgressBar)findViewById(R.id.progressBar1);

在onProgressChanged()函数中,使用以下代码:

myProgress.setProgress(progress * 100);

使用MyActivity.this.setProgress()的替代方法。

另外,如果要使ProgressBar出现在WebView前面,不能使用LinearLayout。请使用centerInParent="true"的RelativeLayout,并在布局中将ProgressBar放在WebView后面。


我显然在你的代码中做了以下更改。MyActivity => MainActivity,myWebView更改为web和WebvView更改为WebView。 - agriz
使用“内置”进度条技术,您实际上根本不需要WebViewClient,只需要WebChromeClient。 - CSmith
这是我现在拥有的。我更新了问题。应用程序仍然无法运行而停止! - agriz
getWindow().requestFeature(Window.FEATURE_PROGRESS); 这一行代码必须在 setContentView 之前添加。但链接正在浏览器中打开! - agriz
我仍然需要使用WebClientView在应用程序中加载页面。 - agriz
显示剩余2条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接