触摸来自另一个线程的视图
Touch views from another thread
OnScrollChanged
方法多次触发。
我只使用 Timer
来检测最后一个滚动条。
如何将我的 TextView
更改为另一个 Thread
?
代码
public class MainActivity : Activity
{
protected override void OnCreate(Bundle bundle)
{
...
}
public class UsefulScrollView : HorizontalScrollView
{
...
private static System.Threading.Timer timer;
protected override void OnScrollChanged(int l, int t, int oldl, int oldt)
{
if (timer == null)
{
TimerCallback tcb = CheckStatus;
timer = new Timer(tcb, null, 500, Timeout.Infinite);
}
else
{
timer.Change(Timeout.Infinite, Timeout.Infinite);
timer.Change(500, Timeout.Infinite);
}
}
protected void CheckStatus(Object stateInfo)
{
TextView tv = linearLayout.FindViewById<TextView>(101);
tv.Text = "abc" // error
}
}
}
异常
ERROR: Only the original thread that created a view hierarchy can touch its views
只是不要 ScrollHelper
是静态的。它不需要是。然后你可以在你的 UsefulScrollView
中引用它并且 ScrollHelper
将能够从它的封闭 class 访问字段,例如 linearLayout
并且能够编辑 TextView
。你尝试使用 MainActivity.RunOnUiThread
是对的,但你可能不必看到所有这些都来自主线程(通过 OnScrollChanged
方法)
OnScrollChanged
方法多次触发。
我只使用 Timer
来检测最后一个滚动条。
如何将我的 TextView
更改为另一个 Thread
?
代码
public class MainActivity : Activity
{
protected override void OnCreate(Bundle bundle)
{
...
}
public class UsefulScrollView : HorizontalScrollView
{
...
private static System.Threading.Timer timer;
protected override void OnScrollChanged(int l, int t, int oldl, int oldt)
{
if (timer == null)
{
TimerCallback tcb = CheckStatus;
timer = new Timer(tcb, null, 500, Timeout.Infinite);
}
else
{
timer.Change(Timeout.Infinite, Timeout.Infinite);
timer.Change(500, Timeout.Infinite);
}
}
protected void CheckStatus(Object stateInfo)
{
TextView tv = linearLayout.FindViewById<TextView>(101);
tv.Text = "abc" // error
}
}
}
异常
ERROR: Only the original thread that created a view hierarchy can touch its views
只是不要 ScrollHelper
是静态的。它不需要是。然后你可以在你的 UsefulScrollView
中引用它并且 ScrollHelper
将能够从它的封闭 class 访问字段,例如 linearLayout
并且能够编辑 TextView
。你尝试使用 MainActivity.RunOnUiThread
是对的,但你可能不必看到所有这些都来自主线程(通过 OnScrollChanged
方法)