1
我有一個初學者的xamarin應用程序。我的MainActivity上有一個按鈕,點擊後會加載第二個活動,同時還有一個按鈕。點擊即按鈕會增加一個計數器(就像helloworld應用程序一樣)。Xamarin兩個活動每個都有一個按鈕:第二個活動按鈕onClick似乎在活動開始之前就已經綁定了
這裏是我的MainActivity:
[Activity(Label = "SpellbookXamarin", MainLauncher = true, Icon = "@drawable/icon")]
public class MainActivity : Activity
{
int count = 1;
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
// Set our view from the "main" layout resource
SetContentView(Resource.Layout.Main);
// Get our button from the layout resource,
// and attach an event to it
Button myButton = FindViewById<Button>(Resource.Id.MyButton);
myButton.Click += (sender, e) =>
{
var intent = new Intent(this, typeof(SpellActivity));
StartActivity(intent);
};
}
}
這是我的SpellActivity:
[Activity(Label = "Spell")]
public class SpellActivity : Activity
{
protected override void OnCreate(Bundle savedInstanceState)
{
int count = 0;
base.OnCreate(savedInstanceState);
// and attach an event to it
Button spellbutton = FindViewById<Button>(Resource.Id.MyButton);
spellbutton.Click += delegate { spellbutton.Text = string.Format("{0} clicks!", count++); };
// Create your application here
}
}
每當我加載應用程序,並單擊MyButton
(一個在MainActivity),一個NullReferenceException
發生引用spellButton的單擊事件。但是這不應該發生。
完美!非常感謝! –