我正在尝试为Click事件声明ImageButton
,但是给出了错误。
是什么会给这个错误?
(btnSettingsBack.Click += btnSettingsBack_Click;
发生错误
MainActivity代码(OnCreate):
ImageButton btnSettings = FindViewById<ImageButton>(Resource.Id.btnSettings);
ImageButton btnSettingsBack = FindViewById<ImageButton>(Resource.Id.btnSettingsBack);
btnAdd = FindViewById<Button>(Resource.Id.btnAdd);
lvNotes = FindViewById<ListView>(Resource.Id.lvNotes);
dbHelper = new DbHelper(this);
//Load Data
LoadNoteList();
btnAdd.Click += BtnAdd_Click;
btnSettings.Click += BtnSettings_Click;
btnSettingsBack.Click += BtnSettingsBack_Click;
}
错误:
更新1: Settings.axml布局代码:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#fff"
android:minWidth="25px"
android:minHeight="25px">
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="80dp"
android:id="@+id/linearLayout1"
android:padding="20px"
android:background="#22A7F0">
<ImageButton
android:src="@drawable/menu_back"
android:background="#22A7F0"
android:layout_weight="0.6"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_margin="30px"
android:id="@+id/btnSettingsBack"
android:layout_gravity="center" />
更新2: OnCreate代码
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
// Set our view from the "main" layout resource
SetContentView(Resource.Layout.Main);
ActionBar.Hide();
ImageButton btnSettings = FindViewById<ImageButton>(Resource.Id.btnSettings);
ImageButton btnSettingsBack = FindViewById<ImageButton>(Resource.Id.btnSettingsBack);
btnAdd = FindViewById<Button>(Resource.Id.btnAdd);
lvNotes = FindViewById<ListView>(Resource.Id.lvNotes);
dbHelper = new DbHelper(this);
//Load Data
LoadNoteList();
btnAdd.Click += BtnAdd_Click;
btnSettings.Click += BtnSettings_Click;
btnSettingsBack.Click += BtnSettingsBack_Click;
}
最佳答案
您正在将名为 Main.axml 的文件设置为 Activity 的contentView。
SetContentView(Resource.Layout.Main);
但是,您在另一个名为 Settings.axml的文件中定义了
ImageButton
。这就是
btnSettingsBack
为null并因此出错的原因。这些控件中的每一个都必须存在于您设置为页面的ContentView的Layout中。如果不存在任何一个,则在尝试访问它时将出现NullReferenceException。
ImageButton btnSettings = FindViewById<ImageButton>(Resource.Id.btnSettings);
ImageButton btnSettingsBack = FindViewById<ImageButton>(Resource.Id.btnSettingsBack);
btnAdd = FindViewById<Button>(Resource.Id.btnAdd);
可以将
FindViewById
视为使用传递的ResourceId查询提供给Activity的Layout的一种方式。如果没有提供此ID,则此方法将不会投诉,但它将返回Null,因此我们的工作是确保您传递的每个ID都是您要设置的布局的一部分。
关于c# - 声明按钮单击时出错-Android C#Xamarin,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44138083/