Malucs Malucs - 4 months ago 27
Android Question

How to this without repeating code? Xamarin - Android

i don't want to repeat this code all times:

Button btnClicks = FindViewById<Button>(Resource.Id.MyButton);
Button btnWarning = FindViewById<Button>(Resource.Id.ButtonWarning);


How i can improve this code to look more clean?
This spam of code can really affect the performance of the application?

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");
}

Answer

Make the buttons class variables and then in 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;
}

now,

private void btnWarn(object sender, EventArgs e)
{
   btnWarning.Text = string.Format("Warning Test");
}