2017-04-10 107 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

我已经提到了主布局代码......错误是一样的......我在构建过程中没有收到通知......但是在运行时 –

相关问题