2017-04-10 1 views
0

サンプルのアンドロイドアプリをテストしていましたが、ボタンハンドラの作成時にエラーが発生しました。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

ええ..私のビルドは成功! @ジェイソン –

+0

それは私が推測するレイアウトの問題かもしれません..?私はLinearからRelativeに変更しました! –

答えて

1

ライン:

SetContentView (Resource.Layout.Main); 

は、それは、非常に重要です実際にあなたのアクティビティのレイアウトを設定するものです。これがなければFindViewByIdは常にnullを返します。

適切なビューを膨張させるか、またはビューを作成します。

+0

彼は正しいです、あなたは使用するレイアウトをアンドロイドに伝えていません – CDrosos

+0

私はすでにそれを持っていません...私は@Cheesebaronしかしここでそれを言及しませんでした。さて、私はリニアレイアウトから相対レイアウトに変更しました。 –

+0

私はメインレイアウトコードについて言及しました...エラーは同じです...私はビルド中に通知されていませんが、実行時に –

関連する問題