Abd*_*rim 0 c# android xamarin
我还是c#的新手,我不知道如何每隔10秒调用一次updateTime()方法
public class MainActivity : Activity
{
TextView timerViewer;
private CountDownTimer countDownTimer;
protected override void OnCreate (Bundle bundle)
{
base.OnCreate (bundle);
SetContentView (Resource.Layout.Main);
timerViewer = FindViewById<TextView> (Resource.Id.textView1);
// i need to invoke this every ten seconds
updateTimeinViewer();
}
protected void updateTimeinViewer(){
// changes the textViewer
}
}
Run Code Online (Sandbox Code Playgroud)
如果有办法创建一个新的线程或类似的东西,我会很乐意得到一些帮助.
我正在使用Xamarin Studio
1 - 在C#中执行此操作的一种常用方法是使用a System.Threading.Timer,如下所示:
int count = 1;
TextView timerViewer;
private System.Threading.Timer timer;
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
SetContentView(Resource.Layout.Main);
timerViewer = FindViewById<TextView>(Resource.Id.textView1);
timer = new Timer(x => UpdateView(), null, TimeSpan.FromSeconds(10), TimeSpan.FromSeconds(10));
}
private void UpdateView()
{
this.RunOnUiThread(() => timerViewer.Text = string.Format("{0} ticks!", count++));
}
Run Code Online (Sandbox Code Playgroud)
请注意,您需要使用Activity.RunOnUiThread()以避免在访问UI元素时发生跨线程冲突.
2 - 另一种更干净的方法是利用C#的异步语言级支持,这样就无需手动封送到UI线程:
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
SetContentView(Resource.Layout.Main);
timerViewer = FindViewById<TextView>(Resource.Id.textView1);
RunUpdateLoop();
}
private async void RunUpdateLoop()
{
int count = 1;
while (true)
{
await Task.Delay(1000);
timerViewer .Text = string.Format("{0} ticks!", count++);
}
}
Run Code Online (Sandbox Code Playgroud)
请注意,Activity.RunOnUiThread()这里没有必要.C#编译器自动计算出来.
| 归档时间: |
|
| 查看次数: |
5801 次 |
| 最近记录: |