我的应用有问题。首先,我使用片段制作了两个标签,这些标签会使活动膨胀。实现的选项卡工作正常。其次,我已经显示了 XAML 。
但是,我现在需要以异步方式运行某些内容 片段中的OnCreateView。如何在不出错的情况下进行管理?
非常感谢任何帮助!谢谢
这是我的片段:
public class FragmentSettings : SupportFragment
{
private Button mBtnOk;
public FragmentSettings(Context context)
{
mContext = context;
}
public override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
}
public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
//Inflate the fragment XML
View view = inflater.Inflate(Resource.Layout.FragmentSettings, container, false);
//Grab the butten from the inflated fragment
mBtnOk = view.FindViewById<Button>(Resource.Id.mBtnOk);
mBtnOk.Click += (object sender, EventArgs e) =>
{
//DO stuff
};
//=====================================
//Want to do something async stuff here
//=====================================
return view;
}
}
答案 0 :(得分:3)
这对我来说很有把握,感谢所有答案!
public override async void OnActivityCreated(Bundle savedInstanceState)
{
base.OnActivityCreated(savedInstanceState);
await LoadData();
}
private async Task LoadData()
{
//My async method
}
答案 1 :(得分:0)
例如,您可以直接运行
AsyncTask
就这样说:
new AsyncTask<Void, Void, Void>() {
@Override
protected Void doInBackground(Void... voids) {
//do your work here
return null;
}
}.execute();
答案 2 :(得分:-1)
如果您需要在后台完成任务,我会使用Backgroundworker:
BackgroundWorker bworker;
public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
//Inflate the fragment XML
View view = inflater.Inflate(Resource.Layout.FragmentSettings, container, false);
//Grab the butten from the inflated fragment
mBtnOk = view.FindViewById<Button>(Resource.Id.mBtnOk);
mBtnOk.Click += (object sender, EventArgs e) =>
{
//DO stuff
};
//Start background task
bworker = new BackgroundWorker();
bworker.DoWork += Bworker_DoWork;
bworker.RunWorkerCompleted += Bworker_RunWorkerCompleted;
bworker.RunWorkerAsync();
return view;
}
private void Bworker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
//Do stuff when the operation is completed
bworker.RunWorkerAsync();
}
private void Bworker_DoWork(object sender, DoWorkEventArgs e)
{
//Do the work in the background
}
编辑:要使其连续运行,您可以在Bworker_RunWorkerCompleted方法中启动backgroundworker agin。 (见方法)
我只是不认为这是实现连续线程的好方法,因为我觉得它会占用大量内存。你可以试试。