有一个不确定的progressBar
,它会一直旋转,直到ListView
内容准备好显示。 progressBar
和listView
都属于同一Fragment
。
因此,我将progressBar
编码为可访问内容,并从获取内容的AsyncTask
中删除。
mProgressBar = (ProgressBar) view.findViewById(R.id.progressbar);
mProgressBar.getIndeterminateDrawable()
.setColorFilter(getResources().getColor(R.color.pink), PorterDuff.Mode.MULTIPLY);
new MyAsyncTask().execute();
//then in asynctask
private class MyAsyncTask extends AsyncTask<Void, Integer, MyAdapter> {
@Override
protected void onPreExecute() {
mProgressBar.setVisibility(View.VISIBLE);
}
@Override
protected MyAdapter doInBackground(Void... params) {
//do the stuff and return loaded adapter
return adapter;
}
@Override
protected void onPostExecute(MyAdapter adapter) {
mProgressBar.setVisibility(View.GONE);
}
}
然而progressBar
被冻结且无法旋转?!
我尝试从progressBar
实例化onPreExecute
,但外部progressBar
不接受我在AsyncTask
内设置的参数。我可以看到,因为它以默认颜色显示而不是自定义。
那我怎样才能控制这个progressBar
?现在我只需要在内容开始加载时显示它,并在它准备好显示时隐藏它。
注意:我在每个项目中都不需要progressBar
,但我需要的方式与我描述的方式相同。
答案 0 :(得分:0)
您是否尝试为MyAsyncTask创建构造函数并将progressBar作为参数提供?
您可以像在任何其他Java类中一样保存私有属性。
编辑:我会定义一个自定义处理程序并从活动中调用它,并使用progressBar的可见性进行播放。
public final class LoadingDialogHandler extends Handler {
private final WeakReference<Activity> mActivity;
// Constants for Hiding/Showing Loading dialog
public static final int HIDE_LOADING_DIALOG = 0;
public static final int SHOW_LOADING_DIALOG = 1;
private View mLoadingDialogContainer;
public LoadingDialogHandler(Activity activity, View container) {
mActivity = new WeakReference<Activity>(activity);
mLoadingDialogContainer = container;
}
public void handleMessage(Message msg) {
Activity activity = mActivity.get();
if (activity == null) {
return;
}
if (msg.what == SHOW_LOADING_DIALOG) {
mLoadingDialogContainer.setVisibility(View.VISIBLE);
} else if (msg.what == HIDE_LOADING_DIALOG) {
mLoadingDialogContainer.setVisibility(View.GONE);
}
}
}
并称之为:
在您的活动/片段中,声明句柄是一个关联进度条:
LoadingDialogHandler loadingDialogHandler = new LoadingDialogHandler(yourActivity, findViewById(R.id.loading_indicator));
显示/隐藏(显示样本):
loadingDialogHandler.sendEmptyMessage(LoadingDialogHandler.SHOW);
PS:也许你必须在这样的UIthread中运行它:
activity.runOnUiThread(new Runnable() {
public void run() {
//update progressBar
}
});
答案 1 :(得分:0)
就是这么简单,有一个用于该功能的内置API:
mProgressBar = (ProgressBar) view.findViewById(R.id.progressbar);
listView.setEmptyView(mProgressBar);
完成!当列表为空或不是
时,listView将自动使用GONE和VISIBLE调用setVisibility