首页 > 解决方案 > 如何在一定时间后显示 ProgressBar

问题描述

我正在使用 Android API 级别 23 (Android 6)。我正在使用 com.loopj.android.http.AsyncHttpClient 来实现与我的后端服务器的异步通信,它工作正常。

在与服务器通信时,我显示了一个进度条,如下所示:

findViewById(R.id.loadingPanel).setVisibility(View.VISIBLE);

并像这样隐藏它:

findViewById(R.id.loadingPanel).setVisibility(View.GONE);

按照此处的建议完成后。

它工作得非常好。

现在大多数时候,对服务器的请求只需要几毫秒,因此显示和隐藏进度条会导致一些闪烁,如果请求时间很短,这是不必要的和烦人的。

什么是仅在请求开始后一定时间后才显示进度条的好方法,比如说在一秒钟后?

标签: androidandroid-progressbarandroid-threading

解决方案


我猜你做了类似以下的事情

 AsyncHttpClient client = new AsyncHttpClient();
 client.get("https://www.example.com", new AsyncHttpResponseHandler() {

    @Override
    public void onStart() {
        // called before request is started
       findViewById(R.id.loadingPanel).setVisibility(View.VISIBLE);
    }

    @Override
    public void onSuccess(int statusCode, Header[] headers, byte[] response) {
        // called when response HTTP status is "200 OK"
        findViewById(R.id.loadingPanel).setVisibility(View.GONE);
    }

    @Override
    public void onFailure(int statusCode, Header[] headers, byte[] errorResponse, Throwable e) {
        // called when response HTTP status is "4XX" (eg. 401, 403, 404)
    }

    @Override
    public void onRetry(int retryNo) {
        // called when request is retried
    }
});

只需尝试以下操作

boolean showProgress= true;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    AsyncHttpClient client = new AsyncHttpClient();
    client.get("https://www.google.com", new AsyncHttpResponseHandler() {

        @Override
        public void onStart() {
            // called before request is started
            //findViewById(R.id.loadingPanel).setVisibility(View.VISIBLE);

            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    if(showProgress){
                        findViewById(R.id.loadingPanel).setVisibility(View.VISIBLE);
                    }
                }
            }, 5*1000); // your progress will start after 5 seconds
        }

        @Override
        public void onSuccess(int statusCode, Header[] headers, byte[] response) {
            // called when response HTTP status is "200 OK"
            //findViewById(R.id.loadingPanel).setVisibility(View.GONE);
            showProgress = false;
        }

        @Override
        public void onFailure(int statusCode, Header[] headers, byte[] errorResponse, Throwable e) {
            // called when response HTTP status is "4XX" (eg. 401, 403, 404)
            showProgress = false;
        }

        @Override
        public void onRetry(int retryNo) {
            // called when request is retried
        }
    });
}

推荐阅读