gpt4 book ai didi

android - 如何使用 RunOnUiThread 更新屏幕上的一些 TextView

转载 作者:搜寻专家 更新时间:2023-11-01 08:56:52 26 4
gpt4 key购买 nike

好吧,我知道这个一般性问题已经在这里被问了很多次,但我还没有找到对我来说有意义的答案。我看到的几乎每个答案都只是说了一些类似的话,“嘿,只要把这个扔进你的方法就可以了”,但我没有看到完整的例子,而且我试过的也没有用。

这是我收到的错误:

[mono] android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.

所以,简单地说,我有一个 Activity ,它从 Web 服务中获取一些信息,然后将 Web 服务结果放入几个 TextView 中。有人可以帮我弄清楚我需要在哪里以及如何使用 RunOnUiThread() 吗?这是代码:


using Android.App;
using Android.OS;
using System;
using System.Web;
using System.Net;
using System.IO;
using Newtonsoft.Json;
using Android.Widget;

namespace DispatchIntranet
{
[Activity (Label = "@string/Summary")]
public class SummaryActivity : Activity
{
private static readonly Log LOG = new Log(typeof(SummaryActivity));
private TextView summaryTotalRegularLabel;
private TextView summaryTotalRollover;
private TextView summaryScheduledLabel;
private TextView summaryRemainingRegular;
private string url;

protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);

// SET THE LAYOUT TO BE THE SUMMARY LAYOUT
SetContentView(Resource.Layout.Summary);

// INITIALIZE CLASS MEMBERS
init();

if (LOG.isInfoEnabled())
{
LOG.info("Making call to rest endpoint . . .");

if (LOG.isDebugEnabled())
{
LOG.debug("url: " + this.url);
}
}

try
{
// BUILD REQUEST FROM URL
HttpWebRequest httpReq = (HttpWebRequest)HttpWebRequest.Create(new Uri(this.url));

// SET METHOD TO 'GET'
httpReq.Method = GetString(Resource.String.web_service_method_get);

// ASK FOR JSON RESPONSE
httpReq.Accept = GetString(Resource.String.web_service_method_accept);

// INVOKE ASYNCHRONOUS WEB SERVICE
httpReq.BeginGetResponse((ar) => {
HttpWebRequest request = (HttpWebRequest)ar.AsyncState;

using (HttpWebResponse response = (HttpWebResponse)request.EndGetResponse (ar))
{
using (StreamReader reader = new StreamReader(response.GetResponseStream()))
{
// PUT RESPONSE INTO STRING
string content = reader.ReadToEnd();

// CONVERT STRING TO DYNAMIC JSON OBJECT
var json = JsonConvert.DeserializeObject<dynamic>(content);

if (LOG.isDebugEnabled())
{
LOG.debug("content: " + content);
LOG.debug("json: " + json);

LOG.debug("TOTAL_REGULAR_PTO_HOURS: " + json.d[0].TOTAL_REGULAR_PTO_HOURS);
}

// ** THIS IS WHAT WILL NOT WORK **
this.summaryTotalRegularLabel.Text = json.d[0].TOTAL_REGULAR_PTO_HOURS;
this.summaryTotalRollover.Text = json.d[0].TOTAL_ROLLOVER_PTO_HOURS;
this.summaryScheduledLabel.Text = json.d[0].TOTAL_USED_PTO_HOURS;
this.summaryRemainingRegular.Text = json.d[0].TOTAL_REMAINING_PTO_HOURS;
}
}
}, httpReq);
}
catch (Exception e)
{
LOG.error("An exception occurred while attempting to call REST web service!", e);
}
}

private void init()
{
// GET GUID FROM PREVIOUS INTENT AND DETERMINE CURRENT YEAR
string guid = Intent.GetStringExtra("guid");
int year = DateTime.Now.Year;

// BUILD URL
this.url = GetString(Resource.String.web_service_url)
+ GetString(Resource.String.ws_get_pto_summary)
+ "?" + "guid='" + HttpUtility.UrlEncode(guid) + "'"
+ "&" + "year=" + HttpUtility.UrlEncode(year.ToString());

// GET THE SUMMARY LABELS
this.summaryTotalRegularLabel = FindViewById<TextView>(Resource.Id.SummaryTotalRegular);
this.summaryTotalRollover = FindViewById<TextView>(Resource.Id.summaryTotalRollover);
this.summaryScheduledLabel = FindViewById<TextView>(Resource.Id.summaryScheduledLabel);
this.summaryRemainingRegular = FindViewById<TextView>(Resource.Id.SummaryRemainingRegular);
}
}
}

最佳答案

当您进行网络服务调用时,HttpWebRequest 会创建一个新线程来运行该操作。这样做是为了防止您的用户界面锁定或跳帧。 Web 服务调用完成后,您需要返回到 UI 线程以更新该线程上的 UI 组件。您可以通过几种不同的方式做到这一点。

首先,您可以像这样将代码包装在匿名函数调用中:

RunOnUiThread(()=>{
this.summaryTotalRegularLabel.Text = json.d[0].TOTAL_REGULAR_PTO_HOURS;
this.summaryTotalRollover.Text = json.d[0].TOTAL_ROLLOVER_PTO_HOURS;
this.summaryScheduledLabel.Text = json.d[0].TOTAL_USED_PTO_HOURS;
this.summaryRemainingRegular.Text = json.d[0].TOTAL_REMAINING_PTO_HOURS;
});

或者您可以通过 RunOnUiThread 调用一个函数(jsonPayload 是类上的一个字段):

jsonPayload = json;
RunOnUiThread(UpdateTextViews);

...


void UpdateTextViews()
{
this.summaryTotalRegularLabel.Text = jsonPayload.d[0].TOTAL_REGULAR_PTO_HOURS;
this.summaryTotalRollover.Text = jsonPayload.d[0].TOTAL_ROLLOVER_PTO_HOURS;
this.summaryScheduledLabel.Text = jsonPayload.d[0].TOTAL_USED_PTO_HOURS;
this.summaryRemainingRegular.Text = jsonPayload.d[0].TOTAL_REMAINING_PTO_HOURS;

}

关于android - 如何使用 RunOnUiThread 更新屏幕上的一些 TextView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18390830/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com