如何在monodroid中使用System.Timers.Timer禁用按钮?

时间:2013-08-08 16:00:08

标签: c# xamarin.android xamarin

我使用monodroid制作Android应用程序。我想在3秒后禁用视图中的按钮。我使用以下代码:

 t = new System.Timers.Timer();
 t.Interval = 3000;
 t.Elapsed += new System.Timers.ElapsedEventHandler(t_Elapsed);
 t.Start();


 protected void t_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
 {
    try{
       t.Stop();
       button.Enabled = false;
    catch(){
       Console.WriteLine("Exception: "+ex);       
    }
 }

由于此代码,我遇到以下异常:

 Android.Util.AndroidRuntimeException: Exception of type 'Android.Util.AndroidRuntimeException' was thrown.
 at Android.Runtime.JNIEnv.CallVoidMethod (IntPtr jobject, IntPtr jmethod, Android.Runtime.JValue[] parms) [0x00023] in /Users/builder/data/lanes/monodroid-mlion-monodroid-4.8.0-branch/3f1c339b/source/monodroid/src/Mono.Android/src/Runtime/JNIEnv.g.cs:368 
 at Android.Views.View.set_Enabled (Boolean value) [0x00043] in /Users/builder/data/lanes/monodroid-mlion-monodroid-4.8.0-branch/3f1c339b/source/monodroid/src/Mono.Android/platforms/android-8/src/generated/Android.Views.View.cs:2341 
 at MyProject.MainActivity.t_Elapsed (System.Object sender, System.Timers.ElapsedEventArgs e) [0x0001e] in /Users/Piscean/Documents/Xamarin Development/MyProject/MyProject/MainActivity.cs:361 
 --- End of managed exception stack trace ---
 android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.
at android.view.ViewRootImpl.checkThread(ViewRootImpl.java:4607)
at android.view.ViewRootImpl.invalidateChildInParent(ViewRootImpl.java:867)
at android.view.ViewGroup.invalidateChild(ViewGroup.java:4066)
at android.view.View.invalidate(View.java:10193)
at android.widget.TextView.invalidateDrawable(TextView.java:4584)
at android.graphics.drawable.DrawableContainer.invalidateDrawable(DrawableContainer.java:250)
at android.graphics.drawable.Drawable.invalidateSelf(Drawable.java:350)
at android.graphics.drawable.Drawable.setVisible(Drawable.java:546)
at android.graphics.drawable.DrawableContainer.selectDrawable(DrawableContainer.java:307)
at android.graphics.drawable.StateListDrawable.onStateChange(StateListDrawable.java:106)
at android.graphics.drawable.Drawable.setState(Drawable.java:462)
at android.view.View.drawableStateChanged(View.java:13998)
at android.widget.TextView.drawableStateChanged(TextView.java:3164)
at android.view.View.refreshDrawableState(View.java:14012)
at android.view.View.setEnabled(View.java:5543)
at android.widget.TextView.setEnabled(TextView.java:1201)
at dalvik.system.NativeStart.run(Native Method)

任何想法如何在3秒后禁用按钮。提前谢谢。

1 个答案:

答案 0 :(得分:4)

关键是这一行:“只有创建视图层次结构的原始线程才能触及其视图。”

由于您的计时器在后台线程上运行,如果您想修改UI,您需要使用该活动的RunOnUiThread方法。

 protected void t_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
 {
    try{
       t.Stop();
       MainActivity.RunOnUiThread(() => { button.Enabled = false; });
    catch(){
       Console.WriteLine("Exception: "+ex);       
    }
 }