我不想一直重复这段代码:
Button btnClicks = FindViewById<Button>(Resource.Id.MyButton);
Button btnWarning = FindViewById<Button>(Resource.Id.ButtonWarning);
如何改进此代码以使其看起来更干净? 这个代码垃圾邮件真的会影响应用程序的性能吗?
protected override void OnResume()
{
base.OnResume();
Button btnClicks = FindViewById<Button>(Resource.Id.MyButton);
Button btnWarning = FindViewById<Button>(Resource.Id.ButtonWarning);
btnWarning.Click += btnWarn;
}
protected override void OnPause()
{
base.OnPause();
Button btnClicks = FindViewById<Button>(Resource.Id.MyButton);
Button btnWarning = FindViewById<Button>(Resource.Id.ButtonWarning);
btnWarning.Click -= btnWarn;
}
private void btnWarn(object sender, EventArgs e)
{
Button btnWarning = FindViewById<Button>(Resource.Id.ButtonWarning);
btnWarning.Text = string.Format("Warning Test");
}
答案 0 :(得分:1)
使按钮类变量,然后在OnCreate
:
Button btnClicks;
Button btnWarning;
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
btnClicks = FindViewById<Button>(Resource.Id.MyButton);
btnWarning = FindViewById<Button>(Resource.Id.ButtonWarning);
btnWarning.Click += btnWarn;
}
现在,
private void btnWarn(object sender, EventArgs e)
{
btnWarning.Text = string.Format("Warning Test");
}
答案 1 :(得分:1)
你真的需要在暂停时删除Click
处理程序吗?
通常在OnCreate
中初始化处理程序就足够了。
如果您确实需要多次访问视图,请在Activity
类本身中保留对视图的引用:
class MyActivity : Activity
{
Button myButton;
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
var myButton = FindViewById<Button>(Resource.Id.MyButton);
}
protected override void OnPause()
{
// do something with myButton
}
}
答案 2 :(得分:0)
每当您订阅某个活动时,您都应该取消订阅以释放附加到该活动的所有内存资源。如果您不取消订阅,最终可能会获得OutOfMemoryException
。实际上,你正确地做了那个部分,但正如其他人提到的,你需要使用OnCreate
来查找一次视图:
Button btnClicks;
Button btnWarning;
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
btnClicks = FindViewById<Button>(Resource.Id.MyButton);
btnWarning = FindViewById<Button>(Resource.Id.ButtonWarning);
}
protected override void OnResume()
{
base.OnResume();
btnWarning.Click += btnWarn;
}
protected override void OnPause()
{
base.OnPause();
btnWarning.Click -= btnWarn;
}