Xamarin Android - Only the original thread that created a view hierarchy can touch its views

时间:2018-01-05 16:06:11

标签: android xamarin xamarin.android

When pressing the login button, it throws an error mentioned despite the async is already used in the button to run the task and the code is correct.

token = await Task.Run(() => { return core.SignIn(username.Text, password.Text); }).ConfigureAwait(false);

1 个答案:

答案 0 :(得分:1)

您正在尝试与主要调度程序在任务中创建的UI元素进行交互。

token = await Task.Run(() => 
{ 
    return core.SignIn(username.Text, password.Text); 
}).ConfigureAwait(false);

需要像:

token = await Task.Run(() => 
{ 
    Activity.RunOnUiThread(()=>{
        return core.SignIn(username.Text, password.Text); 
    });
}).ConfigureAwait(false);

修改

根据您从EditText控件获取用户名和密码的假设进行轻微调整:

token = await Task.Run(() => 
{ 
    string usernm = string.Empty;
    string pass = string.Empty;

    Activity.RunOnUiThread(()=>{
          usernm = username.Text;
          pass = password.Text;
    });

    return core.SignIn(usernm, pass);
}).ConfigureAwait(false);