我正在製作一個示例android應用程序來測試事情,並且創建按鈕處理程序時的錯誤如下,儘管我的構建成功。在Xamarin.Android中運行程序導致創建按鈕處理程序中出現未處理的異常
請幫
錯誤:未處理的異常: System.NullReferenceException:對象不設置到對象的實例。發生
請幫我一個合適的解決方案:
using Android.App;
using Android.Widget;
using Android.OS;
namespace Android_Picture
{
[Activity(Label = "Android Picture", MainLauncher = true, Icon =
"@drawable/icon")]
public class MainActivity : Activity
{
Button ButtonPrev;
Button ButtonNext;
TextView TextTitle;
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
// Set our view from the "main" layout resource
SetContentView (Resource.Layout.Main);
ButtonPrev = FindViewById<Button>(Resource.Id.buttonPrev);
ButtonNext = FindViewById<Button>(Resource.Id.buttonNext);
TextTitle = FindViewById<TextView>(Resource.Id.textTitle);
ButtonPrev.Click += ButtonPrev_Click; //error
ButtonNext.Click += ButtonNext_Click;
}
private void ButtonNext_Click(object sender, System.EventArgs e)
{
TextTitle.Text = "Next Clicked";
//throw new System.NotImplementedException();
}
private void ButtonPrev_Click(object sender, System.EventArgs e)
{
TextTitle.Text = "Previous Clicked";
//throw new System.NotImplementedException();
}
}
}
我Main.axml如下:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
android:text="Prev"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/buttonPrev"
android:layout_alignParentBottom="true" />
<Button
android:text="Next"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/buttonNext"
android:layout_alignParentRight="true"
android:layout_alignParentBottom="true" />
<TextView
android:text="Medium Text"
android:textAppearance="?android:attr/textAppearanceMedium"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/textTitle"
android:layout_centerHorizontal="true"
android:layout_alignParentBottom="true"
android:layout_marginBottom="150dp" />
</RelativeLayout>
是ButtonPrev null?你確定FindViewById調用賦值的成功嗎? – Jason
是的..我的構建成功了! @Jason –
它可能是一個佈局問題,我猜..? Cz ..我從線性變成了相對的一個! –