为什么 text2.Text = "message" 在我的代码中不起作用?

问题描述 投票:0回答:2

为什么 text2.Text = "message" 在我的代码中不起作用? 我想按照下面的源代码在函数中使用它。 我在 Visual Stduio 中使用 Mono for android 在 C# 中进行开发。

源代码:

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 

    }
 }

}

c# android visual-studio xamarin.android
2个回答
5
投票

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";   

    }
 }

2
投票

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 

    }
 }
© www.soinside.com 2019 - 2024. All rights reserved.