【发布时间】:2011-05-08 01:58:16
【问题描述】:
所以,我在这里有我的 onCreate 方法,用于使用用户安装的应用程序填充 ListView。这需要很长时间才能完成,我试图找出在哪里创建一个新线程来完成一些繁重的工作,这样我就可以在列表加载时显示ProgressDialog。这是我的代码:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Find out which prefs to update
Bundle extras = getIntent().getExtras();
if(extras !=null){
buttonPressed = extras.getString("buttonPressed");
loadNumber = extras.getString("loads");
}
buttonPressedAppName = buttonPressed + "AppName" + loadNumber;
buttonPressedAppPack = buttonPressed + "AppPack" + loadNumber;
humanNamePrefs = buttonPressed + "AppText" + loadNumber;
// Get shared preferences
settings = getSharedPreferences(PREFS_NAME, 0);
// Do in another thread to not slow the UI down...eventually
adapter = createAdapter();
setListAdapter(adapter);
}
public ListAdapter createAdapter() {
namesArray = new String[] { "Loading" };
names = new ArrayList<String>();
PackageManager pm = this.getPackageManager();
Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);
mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);
appList = pm.queryIntentActivities(mainIntent, 0);
Collections.sort(appList, new ResolveInfo.DisplayNameComparator(pm));
// Now, appList contains all of the ResolveInfo stuff
for (int i = 0; i < appList.size(); i++) {
names.add(appList.get(i).loadLabel(pm).toString());
}
namesArray = maker(names);
ListAdapter adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, namesArray);
setListAdapter(adapter);
return adapter;
}
我有一个线程来处理列表的排序等,但我的ProgressDialog 甚至在列表完全填充之前都不会出现,这违背了拥有ProgressDialog 的目的。
简而言之,我应该把这个线程放在哪里来显示ProgressDialog,而列表正在完成填充?
回答如下
@Femi 提供了关于AsyncTask 的出色教程,我的ProgressDialog 在加载应用程序列表期间旋转。谢谢!
链接:http://labs.makemachine.net/2010/05/android-asynctask-example/
【问题讨论】:
-
你看过使用异步任务吗?在执行前显示进度,然后在 onPostExecute 中将其关闭
-
查看本教程以查看有效的实现。 p-xr.com/android-tutorial-how-to-make-a-progress-dialog
标签: android multithreading listview progressdialog