【发布时间】:2019-09-12 05:22:16
【问题描述】:
当我尝试运行模拟器时,calculateButton.Click += 委托发生异常,我正在尝试制作一个提示计算器,因此当用户单击按钮时,应用程序开始计算。
例外说 System.NullReferenceException 已抛出对象引用未设置为对象的实例
我尝试了很多东西
Button calculateButton;
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
SetContentView(Resource.Layout.activity_main);
calculateButton = FindViewById<Button>(Resource.Id.calculateButton);
calculateButton.Click += delegate
{
"insert calculations"
};
}
我也试过
Button calculateButton;
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
SetContentView(Resource.Layout.activity_main);
calculateButton = FindViewById<Button>(Resource.Id.calculateButton);
calculateButton.Click += OnCalculateClick;
void OnCalculateClick (object sender, EventArgs e)
{
"insert calculations"
};
}
我希望当我点击按钮时开始计算
编辑: 这是activity_main.axml
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:minWidth="25px"
android:minHeight="25px"
android:id="@+id/linearLayout1">
</LinearLayout >
<include
layout="@layout/content_main" />
<android.support.design.widget.FloatingActionButton
android:id="@+id/fab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|end"
android:layout_margin="@dimen/fab_margin"
app:srcCompat="@android:drawable/ic_dialog_email" />
</android.support.design.widget.CoordinatorLayout>
这里是 content_main.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">
<EditText
android:imeActionId="@+id/inputBill"
android:layout_width ="match_parent"
android:layout_height="wrap_content"
android:id="@+id/editText1"
android:layout_marginBottom="0.0dp"
android:layout_marginTop="0.0dp" />
<Button
android:imeActionId="@+id/calculateButton"
android:layout_width ="match_parent"
android:layout_height="wrap_content"
android:text ="CALCULATE"
android:id="@+id/button1" />
</LinearLayout>
【问题讨论】:
-
FindViewById<Button>(Resource.Id.calculateButton);正在返回null,在activity_main 中是否存在calculateButton? -
@SushiHangover 好吧,我在 content_main.axml 上创建了那个按钮,与 activity_main 相关的唯一代码按钮是 android.support.design.widget.FloatingActionButton ,我从 MainActivity 中删除了它,因为教程告诉我这样做
-
您应该在
activity_mainaxml 中添加一个 id 定义为calculateButton的 Button,因为当前活动是来自Resource.Layout.activity_main的 Inflate -
该教程可能有问题,或者您做错了什么。要运行此代码,您的布局中必须有
calculateButton按钮,并且您没有显示它让我们说是否有。 -
现在可以用了吗?
标签: c# android xamarin events button