开发者

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

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

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜