2017-02-19 90 views
0

我使用Visual Studio。 我試圖更新一個TextView與i.ToString()在for循環一段時間後按下按鈕,但它總是顯示最後一個值,我是新來的android,也許我想念一些東西。任何人都可以解釋我做錯了什麼?xamarin在更新後的循環中更新TextView

namespace MyApp 
{ 
    [Activity(MainLauncher = true, NoHistory = true)] 
    public class MyActivity : Activity 
    { 
     public static TextView text1; 
     protected override void OnCreate(Bundle bundle) 
     { 
      base.OnCreate(bundle); 
      SetContentView(Resource.Layout.MyActivity); 
     } 

     protected override void OnResume() 
     { 
      base.OnResume(); 

      text1 = FindViewById<TextView>(Resource.Id.textView1); 
      Button btn = FindViewById<Button>(Resource.Id.button1); 

      btn.Click += delegate 
      { 
       for(int i=0; i<5; i++) 
       { 
        text1.Text = i.`ToString`(); 
        Task.Delay(1000); 
       } 
      }; 
     } 
    } 
} 

i之後按下按鈕的TextView的值是4。

P.S.對不起,我的英語

回答

0

您要麼讓您的委託異步,然後等待Task.Delay調用或使用計時器。使代理異步看起來像這樣:

 btn.Click += async delegate 
     { 
      for(int i=0; i<5; i++) 
      { 
       text1.Text = i.ToString(); 
       await Task.Delay(1000); 
      } 
     }; 
+0

謝謝,它的工作。我想我應該閱讀一些文檔關於異步,你能幫我一些鏈接? –

+0

@AlexAlexiuc嘗試下面這個開始:https://msdn.microsoft.com/en-us/library/mt674882.aspx – SushiHangover