我有两个文本视图,他们都从同一个对话框中获取文本。以下方法有效。
但是如你所见,我对两个textview都做了同样的事情,唯一的区别是他们的资源ID。有更好的办法吗?
public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
........
var firstPickerDialog = view.FindViewById<ImageView>(Resource.Id.icon1);
firstPickerDialog.Click += OnFirstPickerDialogClick;
var secondPickerDialog = view.FindViewById<ImageView>(Resource.Id.icon2);
secondPickerDialog.Click += OnSecondPickerDialogClick;
return view;
}
void OnFirstPickerDialogClick(object sender, System.EventArgs e)
{
var dialog = new PickerDialogView(ViewModel.Test1);
dialog.DateSelected += (s, date) => ViewModel.Test1 = date;
dialog.Show(((MainView)Activity).SupportFragmentManager, "PickerDialogView");
}
void OnSecondPickerDialogClick(object sender, System.EventArgs e)
{
var dialog = new PickerDialogView(ViewModel.Test2);
dialog.DateSelected += (s, date) => ViewModel.Test2 = date;
dialog.Show(((MainView)Activity).SupportFragmentManager, "PickerDialogView");
}
答案 0 :(得分:3)
也许是这样的?
var firstPickerDialog = view.FindViewById<ImageView>(Resource.Id.icon1);
firstPickerDialog.Click += (s,e) => SelectDate(ViewModel.Test1, d => ViewModel.Test1 = d);
var secondPickerDialog = view.FindViewById<ImageView>(Resource.Id.icon2);
secondPickerDialog.Click += (s,e) => SelectDate(ViewModel.Test2, d => ViewModel.Test2 = d);
void SelectDate(DateTime currentDate, Action<DateTime> setter)
{
var dialog = new PickerDialogView(currentDate);
dialog.DateSelected += (s, date) => setter(date);
dialog.Show(((MainView)Activity).SupportFragmentManager, "PickerDialogView");
}
但这可能会导致内存问题,因为您不会取消注册事件。我是这样做的:
public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
//........
var firstPickerDialog = view.FindViewById<ImageView>(Resource.Id.icon1);
firstPickerDialog.Click += OnFirstPickerDialogClick;
var secondPickerDialog = view.FindViewById<ImageView>(Resource.Id.icon2);
secondPickerDialog.Click += OnSecondPickerDialogClick;
return view;
}
void OnFirstPickerDialogClick(object sender, System.EventArgs e)
{
SelectDate(ViewModel.Test1, d => ViewModel.Test1 = d);
}
void OnSecondPickerDialogClick(object sender, System.EventArgs e)
{
SelectDate(ViewModel.Test2, d => ViewModel.Test2 = d);
}
void SelectDate(DateTime currentDate, Action<DateTime> setter)
{
var dialog = new PickerDialogView(currentDate);
dialog.DateSelected += (s, date) => setter(date);
dialog.Show(((MainView)Activity).SupportFragmentManager, "PickerDialogView");
}
然后你可以简单地调用
firstPickerDialog.Click -= OnFirstPickerDialogClick;
secondPickerDialog.Click -= OnSecondPickerDialogClick;
清理它。您的dialog.DateSelected += ...
有同样的问题。
永远记住小孩:每个+ =应该有一个 - =对方否则内存boogeyman会来找你:)