2017-04-10 111 views
0

我正在製作一個示例android應用程序來測試事情,並且創建按鈕處理程序時的錯誤如下,儘管我的構建成功。在Xamarin.Android中運行程序導致創建按鈕處理程序中出現未處理的異常

Screenshot of the page

請幫

錯誤:未處理的異常: 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> 
+0

是ButtonPrev null?你確定FindViewById調用賦值的成功嗎? – Jason

+0

是的..我的構建成功了! @Jason –

+0

它可能是一個佈局問題,我猜..? Cz ..我從線性變成了相對的一個! –

回答

1

行:

SetContentView (Resource.Layout.Main); 

是非常重要的,它實際上是爲您的活動設置佈局。如果你沒有這個FindViewById將始終返回null。

要麼膨脹正確的視圖,要麼創建一個。

+0

他是對的,你不告訴android要使用哪種佈局 – CDrosos

+0

不,我已經擁有它了......雖然@Cheesebaron沒有提到它。嗯,是的,我從線性佈局更改爲相對佈局。 –

+0

我已經提到了主佈局代碼......錯誤是一樣的......我在構建過程中沒有收到通知......但是在運行時 –

相關問題