为什么text2.Text = "message"在我的代码中不起作用
本文关键字:quot 我的 代码 不起作用 message Text text2 为什么 | 更新日期: 2023-09-27 18:10:30
为什么是text2 ?文本="消息"不工作在我的代码?我想在函数中以这种方式工作,参见代码。我在Visual studio中使用c#开发了Mono for android
源代码:
using System;
using Android.App;
using Android.Content;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Android.OS;
namespace ChatClient_Android
{
[Activity(Label = "ChatClient_Android", MainLauncher = true, Icon = "@drawable/icon")]
public class MainChat : Activity
{
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
// Set our view from the "main" layout resource
SetContentView(Resource.Layout.Main);
// Get our button from the layout resource,
// and attach an event to it
EditText text2 = FindViewById<EditText>(Resource.Id.text2);
}
private void recieved()
{
text2.Text = "mesage"; // The text2 does not existe in this context
}
}
}
EditText text2
不是全局的,而是对方法声明的。把EditText text2;
放到班里。
应该是这样的:
public class MainChat : Activity
{
EditText text2; // <----- HERE
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
SetContentView(Resource.Layout.Main);
text2 = FindViewById<EditText>(Resource.Id.text2);
}
private void recieved()
{
text2.Text = "mesage";
}
}
text2
是在OnCreate
内部定义的,因此received
对它一无所知。
您需要将text2定义为一个类字段,如下所示:
public class MainChat : Activity
{
private EditText text2;
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
// Set our view from the "main" layout resource
SetContentView(Resource.Layout.Main);
// Get our button from the layout resource,
// and attach an event to it
text2 = FindViewById<EditText>(Resource.Id.text2);
}
private void recieved()
{
text2.Text = "mesage"; // The text2 does not existe in this context
}
}