2016-10-09 98 views
0

我正在寫一個android應用程序在c#中,與服務器通信。c#android訪問另一個類的textview

// Set our view from the "main" layout resource 
SetContentView (Resource.Layout.Main); 
Button button = FindViewById<Button>(Resource.Id.button1); 
TextView txt = FindViewById<TextView>(Resource.Id.textView1); 

Client client = new Client(); 
client.Setup("ws://192.168.0.14:8001", "basic", WebSocketVersion.Rfc6455); 
client.Start(); 
... 

在啓動時,它應該在TextView上顯示一個標準。

class Client : Activity{ 
    private WebSocket websocketClient; 
    ... 
    public void Setup(string url, string protocol, WebSocketVersion version) 
    { 
    ... 
    websocketClient.Opened += new EventHandler(websocketClient_Opened); 
    } 

    private void websocketClient_Opened(object sender, EventArgs e){ 
     txt.Text = ("Client successfully connected."); // this line is wrong 
     websocketClient.Send("Hello World!"); 
    } 
} 

的問題是,我不知道,如何存取權限TextView的。我發現this,但我不知道我應該如何使用它在我的情況下

回答

0

只需使WebsocketClient屬性它而不是類變量,然後您可以從您的活動訪問它。

public class MainActivity : Activity 
{ 
    private TextView txt; 
    private Client client; 

    protected override void OnCreate(Bundle bundle) 
    { 
     base.OnCreate(bundle); 
     txt = FindViewById<TextView>(Resource.Id.textView1); 

     client = new Client(); 
     client.WebsocketClient.Opened += websocketClient_Opened; 
     client.Setup("ws://192.168.0.14:8001", "basic", WebSocketVersion.Rfc6455); 
     client.Start(); 
    } 

    protected override void OnDestroy() 
    { 
     client.WebsocketClient.Opened -= websocketClient_Opened; 
     base.OnDestroy(); 
    } 

    private void websocketClient_Opened(object sender, EventArgs e) 
    { 
     txt.Text = ("Client successfully connected."); 
     // maybe have to be wrapped in a RunOnUiThread(() =>{ ... }); 
    } 
} 

class Client 
{ 
    public WebSocket WebsocketClient { get; set; } 

    public void Setup(string url, string protocol, WebSocketVersion version) 
    { 
     // WebsocketClient = new ... 
     WebsocketClient.Opened += websocketClient_Opened; 
    } 

    private void websocketClient_Opened(object sender, EventArgs e) 
    { 
     WebsocketClient.Send("Hello World!"); 
    } 
} 
0

我不知道你用的是什麼庫WebSocket。我使用websocket-sharp。它是示例使用:

 protected override void OnCreate(Bundle bundle) 
     { 
     TextView txt = FindViewById<TextView>(Resource.Id.My); 

     using (var ws = new WebSocket("ws://dragonsnest.far/Laputa")) 
     { 
      ws.OnError += (sender, e) => 
      { 
       txt.Text = e.Message; 
      }; 
      .......... 
     } 

這是工作。我在我的TextView中看到錯誤消息。

如果你得到錯誤,請嘗試使用RunOnUiThread.Example:

private void websocketClient_Opened(object sender, EventArgs e) 
    { 
     this.RunOnUiThread(() => 
       { 
        txt.Text = "your message"; 
       });   
    } 

希望這有助於。