android - 如何在一定时间后显示 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);
按照此处的建议完成后。
它工作得非常好。
现在大多数时候,对服务器的请求只需要几毫秒,因此显示和隐藏进度条会导致一些闪烁,如果请求时间很短,这是不必要的和烦人的。
什么是仅在请求开始后一定时间后才显示进度条的好方法,比如说在一秒钟后?
解决方案
我猜你做了类似以下的事情
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
}
});
}
推荐阅读
- python - 如何让 BeautifulSoup 检测到 ul 中的 li?
- android - 为什么在for循环中从应用程序包获取数据会导致stackoverflow错误
- installation - 无法安装 Dynamics ax 2012 - 错误 OpenDatabase
- neo4j - 如何在 Cypher(Neo4j)中通过给定的面包屑字符串获取路径?
- amazon-web-services - 微服务和 AWS-IoT
- javascript - 试图改变可变井字游戏的价值
- php - 计算时出现未定义变量错误
- bokeh - 如何使用多处理创建许多 Bokeh 图形?
- php - 集成 Codeigniter 和 Wordpress
- javascript - JS中真正的数组和数组迭代器有什么区别