开发者

Why text2.Text = "message" not work in my code?

开发者 https://www.devze.com 2023-04-10 10:08 出处:网络
Why text2.Text = \"message\" not work in my code ? I want to work this way in a function see in code. I developed in Visual Stduio with Mono for android in C#

Why text2.Text = "message" not work in my code ? I want to work this way in a function see in code. I developed in Visual Stduio with Mono for android in C#

The Source code:

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
    }
 }

}


EditText text2 is declared not global but to the method. Put EditText text2; in the class.

Should be like this :

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 is defined inside OnCreate, therefore received knows nothing about it.

You need to define text2 as a class field, like this:

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 

    }
 }
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号