AsyncTasks和ProgressDialogs

时间:2012-09-10 21:43:46

标签: android xamarin.android

我需要使用服务器中的数据列表构建BaseExpandableListAdapters。我正在使用AsyncTask来检索这个值列表。由于我目前无法从DoInBackGround覆盖方法返回BaseExpandableListAdapter,因此我使用的是公共属性。使用以下代码我可以:

  1. 获取我的AsyncTask类的My和Market属性以返回所有预期值但是我的ProgressDialog在执行任务之后才会出现,使其无用,或者
  2. 根据需要立即显示ProgressDialog但是当我尝试使用它们将适配器分配给我的列表视图时,My和Market属性为空
  3. 我需要实现两者。

    public class Work : Activity
    {
        private ExpandableListView market;
        private ExpandableListView my;
    
        protected override void OnCreate(Bundle bundle)
        {
            base.OnCreate(bundle);
    
            SetContentView(Resource.Layout.Work);
    
            market = (ExpandableListView)FindViewById(Resource.Id.market);
            my = (ExpandableListView)FindViewById(Resource.Id.my);
    
            PopulateWorkListViews populate = new PopulateWorkListViews(this);
            populate.Execute(techID, market, userType);
    
            //Removing the following line allows for the ProgressDialog but the Market 
            //and My properties of the PopulateWorkListViews class are empty as opposed 
            //to leaving this line in and both properties contain all expected values 
            //but ProgressDialog doesn't show up.
            string result = populate.Get().ToString();
    
            market.SetAdapter(populate.Market);
            my.SetAdapter(populate.My);
        }
    }
    
    public class PopulateWorkListViews : AsyncTask
    {
        private Context Context { get; set; }
        private ProgressDialog Dialog { get; set; }
        public BaseExpandableListAdapter Market { get; set; }
        public BaseExpandableListAdapter My { get; set; }
    
        public PopulateWorkListViews(Context context)
        {
            Context = context;
        }
    
        protected override void OnPreExecute()
        {
            Dialog = new ProgressDialog(Context);
            Dialog.SetMessage("Processing...");
            Dialog.Window.SetGravity(GravityFlags.Center);
            Dialog.SetCancelable(false);
            Dialog.Indeterminate = true;
            Dialog.SetProgressStyle(ProgressDialogStyle.Spinner);
            Dialog.Show();
        }
    
        protected override Java.Lang.Object DoInBackground(params Java.Lang.Object[] @params)
        {
            WS ws = new WS();
            List<ServiceCall> calls = ws.GetMarketCalls(@params[0].ToString(), @params[1].ToString(), @params[2].ToString()).ToList();
    
            Market = new MarketCallListView(Context, calls);
            My = new MyCallListView(Context, calls, @params[0].ToString());
    
            return "Done";
        }
    
        protected override void OnPostExecute(Java.Lang.Object result)
        {
            Dialog.Dismiss();
        }
    }
    

1 个答案:

答案 0 :(得分:0)

不立即绘制对话框的原因是您在populate.Get()中阻止了UI线程。如果您将SetAdapter底部的两条onCreate行移至onPostExecute,该怎么办?