我的代码有什么问题?

时间:2015-09-27 10:24:10

标签: c# android xamarin

当模拟输出显示未处理的异常时,我的应用程序总是崩溃。 我是android和c#的新手,所以有点耐心会受到赞赏!!

namespace timer2
{   
    [Activity(Label = "timer2", MainLauncher = true, Icon = "@drawable/icon")]

    public class MainActivity : Activity
    {
      static Button start, stop;
      static TextView time;

        protected override void OnCreate(Bundle bundle)
        {
            base.OnCreate(bundle);

            start = FindViewById<Button>(Resource.Id.start);
            stop = FindViewById<Button>(Resource.Id.stop);
            time = FindViewById<TextView>(Resource.Id.textView1);

            SetContentView(Resource.Layout.Main);


            time.Text = "00:03:00";

            Counterclass timer = new Counterclass(180000, 1000);

            start.Click += delegate
            {
                timer.Start();
            };

            stop.Click += delegate
            {
                timer.Cancel();
            };
        }

        public class Counterclass : CountDownTimer
        {
            public Counterclass(long millisInFuture, long countDownInterval)      :base(millisInFuture, countDownInterval)
            {
            }

            public override void OnFinish()
            {
                time.Text = "Ready";
            }

            public override void OnTick(long millisUntilFinished)
            {
                long millis = millisUntilFinished;
                string hms = String.Format("%02d:%02d:%02d", TimeSpan.FromMilliseconds(millis).Hours,
                    TimeSpan.FromMilliseconds(millis).Minutes - TimeSpan.FromHours(TimeSpan.FromMilliseconds(millis).Hours).Minutes,
                    TimeSpan.FromMilliseconds(millis).Seconds - TimeSpan.FromMinutes(TimeSpan.FromMilliseconds(millis).Minutes).Seconds);

                time.Text = hms;
            }
        }
    }
}

1 个答案:

答案 0 :(得分:3)

您需要在找到控件之前设置内容视图:

        protected override void OnCreate(Bundle bundle)
        {
            base.OnCreate(bundle);
            SetContentView(Resource.Layout.Main);

            start = FindViewById<Button>(Resource.Id.start);
            stop = FindViewById<Button>(Resource.Id.stop);
            time = FindViewById<TextView>(Resource.Id.textView1);