【问题标题】:Why text2.Text = "message" not work in my code?为什么 text2.Text = "message" 在我的代码中不起作用?
【发布时间】:2023-03-29 05:45:01
【问题描述】:

为什么 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 

    }
 }

}

【问题讨论】:

  • text2 超出范围。如果您希望在另一个方法中重用它,则需要在方法上方声明它。尝试类似:

标签: c# android visual-studio xamarin.android


【解决方案1】:

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】:

text2OnCreate 内部定义,因此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 

    }
 }

【讨论】:

    猜你喜欢
    • 2014-01-23
    • 2013-08-06
    • 2021-03-17
    • 2018-04-24
    • 2019-01-07
    • 2014-04-28
    • 2017-06-18
    • 2019-03-12
    相关资源
    最近更新 更多