我试图在延迟一段时间后更改TextView的文本。我编写了一个在执行某些操作后调用的方法。
public void Update()
{
Task.Delay(10000).ContinueWith(t =>
{
dotsLoaderView.Hide(); // This works fine
imgOverlay.Visibility = ViewStates.Gone; // This works fine
ll_Info.Visibility = ViewStates.Visible; // This doesn't work
txt_Info.Text = "Some mesage !"; // This doesn't work
});
}
其中ll_info
是包含id txt_info
的textview的线性布局的id。
我查看了我的layout.xml
文件,android:name标签中没有冲突,每个id都不同。当我从任何其他地方更改此textview的文本时,它可以正常工作,但当我尝试更改Task.Delay()
内部时,它无法正常工作。为什么呢?
答案 0 :(得分:1)
必须在UI线程上查看更新。 尝试:
public void Update()
{
Task.Delay(10000).ContinueWith(t =>
{
dotsLoaderView.Hide();
RunOnUiThread(delegate
{
imgOverlay.Visibility = ViewStates.Gone;
ll_Info.Visibility = ViewStates.Visible;
txt_Info.Text = "Some mesage !";
});
});
}
答案 1 :(得分:1)
更新方法以使用async以便更容易继续。
public async Task UpdateAsync() {
await Task.Delay(10000);//Non blocking delay on other thread
//Back on the UI thread
dotsLoaderView.Hide();
imgOverlay.Visibility = ViewStates.Gone;
ll_Info.Visibility = ViewStates.Visible;
txt_Info.Text = "Some mesage !";
}
并在一个凸起事件的处理程序中调用它
public async void Action(object sender, EventArgs e) {
await UpdateAsync();
}
或者在事件处理程序中完成所有事情
private event EventHandler Update = delegate { };
private async void OnUpdate(object sender, EventArgs e) {
await Task.Delay(10000);//Non blocking delay on other thread
//Back on the UI thread
dotsLoaderView.Hide();
imgOverlay.Visibility = ViewStates.Gone;
ll_Info.Visibility = ViewStates.Visible;
txt_Info.Text = "Some mesage !";
}
您使用事件
注册事件处理程序Update += OnUpdate;
并且在执行操作后直接提升事件
Updated(this, EventArgs.Empty);