2011-10-04 102 views
0

爲什麼text2.Text =「message」在我的代碼中不起作用? 我想在函數中以這種方式工作,參見代碼。 我在Visual Stduio在C#開發具有單聲道的Android爲什麼text2.Text =「message」在我的代碼中不起作用?

的源代碼:

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 

    } 
} 

}

+0

文本2超出範圍。如果你希望在另一個方法中重用它,你需要在方法之上聲明它。 嘗試像這樣: – DaveHogan

回答

4

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

    } 
} 
+0

非常感謝:P – Zav

+0

如果這個工作適合您,請不要忘記接受答案。 –

1

text2是內部OnCreate定義,因此received對此一無所知。

您需要定義文本2爲一類領域,如:

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 

    } 
} 
相關問題