c #android从另一个类访问textview

时间:2016-10-09 13:32:04

标签: c# android xamarin

我在c#中编写了一个Android应用程序,它与服务器进行通信。

// 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但我不知道如何在我的情况下使用它

2 个答案:

答案 0 :(得分: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!");
    }
}

答案 1 :(得分: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";
                });        
    }

希望得到这个帮助。