我陷入了从活动1切换到活动2的情况.我使用Thread.sleep(5000)在5秒后启动另一个活动但我想要运行五秒钟的进度条也会在第一个活动中休眠Pleaze帮助我,当我点击第一个活动上的下一个按钮时,进度条会运行五秒,然后应该加载活动我的代码是:
public class Activity1 extends Activity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button next = (Button) findViewById(R.id.B);
final ProgressBar p=(ProgressBar) findViewById(R.id.pr);
next.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
p.setVisibility(4);
Thread t=new Thread();
try{
t.sleep(5000);
}
catch(Exception e){}
Intent myIntent = new Intent(view.getContext(), activity2.class);
startActivityForResult(myIntent, 0);
}
});
}}
Run Code Online (Sandbox Code Playgroud)
为此更改OnClickListener.这不会像你一样阻止你的主线程(这解释了为什么你的应用程序冻结了5秒):
next.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
new AsyncTask<Integer, Long, Boolean>()
{
ProgressDialog pd;
@Override
protected Boolean doInBackground(Integer... params)
{
pd = new ProgressDialog(Activity1.this);
pd.setTitle("Loading Activity");
pd.setMessage("Please Wait ...");
pd.setMax(params[0]);
pd.setIndeterminate(false);
pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
publishProgress(0L);
long start = System.currentTimeMillis();
long waitTime = params[0] * 1000;
try
{
while (System.currentTimeMillis() - start < waitTime)
{
Thread.sleep(500);
publishProgress(System.currentTimeMillis() - start);
}
}
catch (Exception e)
{
return false;
}
return true;
}
@Override
protected void onProgressUpdate(Long... values)
{
if (values[0] == 0)
{
pd.show();
}
else
{
pd.setProgress((int) (values[0] / 1000));
}
}
@Override
protected void onPostExecute(Boolean result)
{
pd.dismiss();
Intent myIntent = new Intent(view.getContext(), activity2.class);
startActivityForResult(myIntent, 0);
}
}.execute(5);
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7303 次 |
| 最近记录: |