我正在尝试在我的片段中放入progressDialog,这样我的应用程序在每个操作之间感觉更顺畅。我遇到的问题是主线程在异步线程修改它之前返回视图。在切换到这个方法之前,我正在做一个Thread.join()。
public class MyFragment extends Fragment {
public View onCreateView(LayoutInflater inflater,ViewGroup container, Bundle args) {
mLLayout = new LinearLayout(getActivity());
mLLayout.setPadding(0, 0, 0, 0);
mLLayout.setOrientation(LinearLayout.VERTICAL);
mScroll = new ScrollView(getActivity().getApplicationContext());
mScroll.setVerticalScrollBarEnabled(true);
mScroll.addView(mLLayout);
new AsyncCaller().execute();
return mScroll;
}
private class AsyncCaller extends AsyncTask<Void, Void, Void>
{
ProgressDialog nDialog = new ProgressDialog(getActivity());
@Override
protected void onPreExecute()
{
super.onPreExecute();
//this method will be running on UI thread
nDialog = new ProgressDialog(getActivity());
nDialog.setMessage("Loading..");
nDialog.setTitle("Checking Network");
nDialog.setIndeterminate(false);
nDialog.setCancelable(true);
nDialog.show();
}
@Override
protected Void doInBackground(Void... params)
{
//Doing http requests and modifying views
return null;
}
@Override
protected void onPostExecute(Void result)
{
super.onPostExecute(result);
//this method will be running on UI thread
nDialog.dismiss();
}
}
...
}
我无法在不阻塞主线程的情况下找到一个解决方案,并且同样没有看到progressDialog,而是有一个很大的延迟。另外,我从未看到我的代码进入“onPostExecute()”。
提前感谢您的帮助!
答案 0 :(得分:0)
直接从我已经完成的应用程序,这段代码应该有所帮助:
ProgressBar mProgress = (ProgressBar) findViewById(R.id.progressBar);
private float mProgressStatus = 0;
private Handler mHandler = new Handler();
private void startProgressBar()
{
new Thread(new Runnable()
{
@Override
public void run()
{
while (mProgressStatus < 100)
{
try
{
Thread.sleep(1000);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
mProgressStatus += 1.3;
mHandler.post(new Runnable()
{
@Override
public void run()
{
mProgress.setProgress((int) mProgressStatus);
}
});
}
}
}).start();
}