我正在开发一个记事本应用程序,并且当关闭[[Note Editor关闭(我正在使用Finish()
关闭编辑器)时,我需要在视图上重新加载笔记。我不确定如何等到活动关闭并执行某些操作。
public async void noteClicked(object sender, EventArgs e)
{
var obj = (RelativeLayout)sender;
var id = obj.Id;
var note = Util.db.Query<Note>(string.Format("SELECT * FROM Notes WHERE ID={0}", id));
var intent = new Intent(this, typeof(EditorAcitivity));
intent.PutExtra("Note", JsonConvert.SerializeObject(note));
intent.PutExtra("Mode", "Edit");
StartActivity(intent);
}
在EditorActivity.cs上:
protected override void OnCreate(Bundle savedInstanceState) { base.OnCreate(savedInstanceState); SetContentView(Resource.Layout.editor_activity); Util.context = this; mode = Intent.GetStringExtra("Mode"); txtTitle = FindViewById<EditText>(Resource.Id.editorTitle); txtText = FindViewById<EditText>(Resource.Id.editorText); if (mode == "Edit") { note = JsonConvert.DeserializeObject<Note>(Intent.GetStringExtra("Note")); txtTitle.Text = note.title; txtText.Text = note.text; } FindViewById<ImageButton>(Resource.Id.editorDelete).Click += editorDelete_Clicked; FindViewById<ImageButton>(Resource.Id.editorSave).Click += editorSave_Clicked; } private void editorSave_Clicked(object sender, EventArgs e) { if (txtText.Text.Length == 0 || string.IsNullOrWhiteSpace(txtText.Text)) { Util.makeShortText("Null text"); } else { var note = new Note(); note.date = Util.now(); note.text = txtText.Text; if (string.IsNullOrWhiteSpace(txtTitle.Text)) { note.title = " "; } else { note.title = txtTitle.Text; } Util.db.Insert(note); this.Finish(); } }
我想在活动结束后做类似loadNotes()
的事情([
this.Finish()
)
编辑:我不想返回一些数据,只需等待活动即可。
StartActivityForResult
var intent = new Intent(this, typeof(EditorAcitivity));
intent.PutExtra("Note", JsonConvert.SerializeObject(note));
intent.PutExtra("Mode", "Edit");
StartActivityForResult(intent,REQUEST_CODE_EDITOR_ACITIVTY);
在那种情况下,REQUEST_CODE_EDITOR_ACITIVTY
是整数常量。然后,当您即将完成活动时,请按如下所示调用
SetResult
方法
Util.db.Insert(note); SetResult(Result.Ok); this.Finish();
最后在与启动OnActivityResult
相同的活动中重写EditorAcitivity
方法,如下所示
protected override void OnActivityResult(int requestCode, [GeneratedEnum] Result resultCode, Intent data) { base.OnActivityResult(requestCode, resultCode, data); if(requestCode == REQUEST_CODE_EDITOR_ACITIVTY) { if(resultCode == Result.Ok) { //Here your activity received the callback and you can call the load notes method loadNotes(); } } }
如果您想了解有关Activity for result
的更多信息,请看一下本教程>