ActionBar 不显示进度条

ActionBar is not showing the progress bar

我有 WebView,我想在 WebView 中加载页面时,在 ActionBar 中显示进度。该应用程序正在使用 AppCompat Android 库,应用程序的目标和编译 SDK 版本为 21。通常只有 WebView 运行。

我认为方法有问题setSupportProgress(int progress)

我的代码如下。

Activity:

public class AuthActivity extends ActionBarActivity {

private boolean isConfirmationRequired = false;
private Utils utils = new Utils();

@SuppressLint("SetJavaScriptEnabled")
@Override
protected void onCreate(Bundle savedInstanceState) {
    supportRequestWindowFeature(Window.FEATURE_PROGRESS);
    super.onCreate(savedInstanceState);

    setContentView(R.layout.activity_auth);

    final String authUrl = "some url";
    final WebView authWebView = (WebView) findViewById(R.id.auth_web_view);
    authWebView.getSettings().setJavaScriptEnabled(true);
    authWebView.setWebChromeClient(new WebChromeClient() {
        @Override
        public void onProgressChanged(WebView view, int newProgress) {
            setTitle(R.string.loading);
            setSupportProgress(newProgress * 100);

            if (newProgress == 100)
                setTitle(R.string.sign_in);
        }
    });

    authWebView.setWebViewClient(new WebViewClient() {
        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            super.onPageStarted(view, url, favicon);
            if (!url.equals(authUrl))
                isConfirmationRequired = true;
        }

        @Override
        public boolean shouldOverrideUrlLoading(WebView webView, String url) {
            boolean hasUserBrokenAuth = url.equals("some url") ||
                    url.equals("some url");
            boolean isUserAuthorized = url.startsWith("some url" +
                    "access_token=");

            if (hasUserBrokenAuth) {
                if (isConfirmationRequired)
                    utils.showConfirmDialog(AuthActivity.this);
                else
                    finish();
            } else {
                utils.webViewLoadUrlIfInternetIsConnected(AuthActivity.this, authWebView, url);
                if (isUserAuthorized)
                    saveAuthData(url);
            }
            return true;
        }
    });

    utils.webViewLoadUrlIfInternetIsConnected(this, authWebView, authUrl);
}

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
    if (keyCode == KeyEvent.KEYCODE_BACK) {
        if (isConfirmationRequired) {
            utils.showConfirmDialog(this);
        }
    }
    return super.onKeyDown(keyCode, event);
}

@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.
    if (isConfirmationRequired) {
        utils.showConfirmDialog(this);
        return true;
    } else {
        return super.onOptionsItemSelected(item);
    }

}

private void saveAuthData(String url) {
    String accessToken = utils.extractPattern(url, "access_token=(.*?)&");
    String userId = utils.extractPattern(url, "user_id=(\d*)");
}

utils.webViewLoadUrlIfInternetIsConnected:

public void webViewLoadUrlIfInternetIsConnected(final Context context, final WebView webView,
                                                final String url) {
    if (isInternetConnected(context)) {
        webView.loadUrl(url);
    } else {
        showSnackbarInternetDisconnected(context, new ActionClickListener() {
            @Override
            public void onActionClicked(Snackbar snackbar) {
                snackbar.dismiss();
                webViewLoadUrlIfInternetIsConnected(context, webView, url);
            }
        });
    }
}

您应该尝试将 ProgressBarVisibility 更新为 setSupportProgressBarVisibility(boolean),如下所示:

// set Visibility to TRUE
setSupportProgressBarVisibility(true); 

然后,在 onProgressChanged 中,在进度结束时禁用其 Visibility

@Override
public void onProgressChanged(WebView view, int newProgress) {
    setTitle(R.string.loading);
    setSupportProgress(newProgress * 100);

    if (newProgress == 100) {
        // set it to FALSE
        setSupportProgressBarVisibility(false);
        setTitle(R.string.sign_in);
    }
    //...
}

更新:

另一种解决方案可能是使用自定义 Progress View 添加到 AppCompat

您必须 inflate 包含水平 ProgressBar 的自定义视图,get ActionBar container ViewGroup 和 添加自定义视图 到容器:

/** Inflate a custom view **/
View ab_progressView = getLayoutInflater().inflate(R.layout.ab_progressbar, null)
/** Get the ActionBar container **/
ViewGroup ab_container = (ViewGroup) findViewById(R.id.action_bar_container);
/** Add the custom view **/
ab_container.addView(ab_progressView);

If ab_container returns a NullPointerException, you just have to create a new Runnable to get its id in a parallel thread.

您必须在 ActionBar 底部设置这个新视图:

/** Create layout parameters **/
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(
     LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
/** Set the gravity **/
params.gravity = Gravity.BOTTOM;
/** Set these params to your view **/
ab_progressView.setLayoutParams(params);

接着更新进度:

/** Get the progress bar **/
final ProgressBar progressBar = (ProgressBar) ab_progressView.findViewById(R.id.progress);

@Override
public void onProgressChanged(WebView view, int newProgress) {
    /** Update the progress **/
    progressBar.setProgress(newProgress * 100);
}

当,进度结束,移除自定义视图即可:

/** Remove the custom view added **/
ab_container.removeView(ab_progressView);

我没有测试这个解决方案,但它应该可以工作..

AppCompat 不支持显示进度视图,因此您可以从代码中删除以下内容:

supportRequestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
setSupportProgressBarIndeterminateVisibility(...);

有可能改用新的工具栏,我今天自己试了一下,但是很复杂。我最终的解决方案是设置一个菜单项更多,该菜单项引用引用抽奖的布局:

<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:app="http://schemas.android.com/apk/res-auto" >

<item
    android:id="@+id/menu_progress"
    android:visible="false"
    app:showAsAction="always"
    app:actionLayout="@layout/progress_indeterminate"
    tools:ignore="AlwaysShowAction,UnusedAttribute"/>

那么布局如下:

<?xml version="1.0" encoding="utf-8"?>
<ProgressBar xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/toolbar_progress_bar"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:indeterminateDrawable="@drawable/custom_progress_wheel" />

drawable如下(您可以根据需要自定义):

<?xml version="1.0" encoding="utf-8"?>
<rotate xmlns:android="http://schemas.android.com/apk/res/android"
    android:fromDegrees="0"
    android:pivotX="50%"
    android:pivotY="50%"
    android:toDegrees="720" >

<shape
    android:innerRadiusRatio="3"
    android:shape="ring"
    android:thicknessRatio="12"
    android:useLevel="false" >

    <gradient
        android:centerColor="#FFFFFF"
        android:centerY="0.50"
        android:endColor="#FFFFFF"
        android:startColor="#000000"
        android:type="sweep"
        android:useLevel="false" />
</shape>
</rotate>

然后在 onCreateOptionsMenu 中使用以下内容初始化 menuItem:

mProgressMenu = menu.findItem(R.id.menu_progress);

使用 setVisibility,您可以在 activity 中的任何位置更改菜单的可见性。