1

我正在使用 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 秒后禁用按钮。提前致谢。

4

1 回答 1

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);       
    }
 }
于 2013-08-08T17:08:03.860 回答