我有xml的代码
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:padding="15px"
>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Loading..."
/>
<ProgressBar android:id="@+id/progressBar"
android:paddingTop="10px"
style="?android:attr/progressBarStyleHorizontal"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:max="100" />
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="@+id/txt"
/>
</LinearLayout>
然后为班级:
public class Loading extends Activity {
ProgressBar bar;
TextView txt;
int total=0;
boolean isRunning=false;
// handler for the background updating
Handler handler=new Handler() {
@Override
public void handleMessage(Message msg) {
total=total+5;
String perc=String.valueOf(total).toString();
txt.setText(perc+"% completed");
bar.incrementProgressBy(5);
}
};
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.loading_bar);
bar=(ProgressBar)findViewById(R.id.progressBar);
txt=(TextView)findViewById(R.id.txt);
}
public void onStart() {
super.onStart();
// reset the bar to the default value of 0
bar.setProgress(0);
// create a thread for updating the progress bar
Thread background=new Thread(new Runnable() {
public void run() {
try {
for (int i=0;i<20 && isRunning;i++) {
// wait 1000ms between each update
Thread.sleep(1000);
handler.sendMessage(handler.obtainMessage());
}
}
catch (Throwable t) {
}
}
});
isRunning=true;
// start the background thread
background.start();
}
public void onStop() {
super.onStop();
isRunning=false;
}
}
有了这个,我把它叫做另一个活动:
public void onClick (View v)
{
switch (v.getId())
{
case R.id.buttonNext3:
Intent Loading = new Intent(this, Loading.class);
startActivity(Loading);
getContent();
Call();
db.generation();
Intent Next3 = new Intent(this, FoodPlanning.class);
startActivity(Next3);
break;
}
}
但它不适用于我的,它只是显示黑屏,但它仍在进行中......我想在我点击按钮时出现加载栏并且过程仍在进行中。任何的想法?你好
答案 0 :(得分:0)
正如Adil所建议的,AsyncTask是运行后台任务的首选方法,它具有在UI线程上运行某些命令的简单选项,同时将其余命令推送到后台。请参阅SDK中的此示例(http://developer.android.com/reference/android/os/AsyncTask.html):
private class DownloadFilesTask extends AsyncTask<URL, Integer, Long> {
protected Long doInBackground(URL... urls) {
int count = urls.length;
long totalSize = 0;
for (int i = 0; i < count; i++) {
totalSize += Downloader.downloadFile(urls[i]);
publishProgress((int) ((i / (float) count) * 100));
}
return totalSize;
}
protected void onProgressUpdate(Integer... progress) {
setProgressPercent(progress[0]);
}
protected void onPostExecute(Long result) {
showDialog("Downloaded " + result + " bytes");
}
}
请注意“onProgressUpdate”方法以及doInBackground。