Xamarin Mono Android实现“再按一次退出程序”

开始研究Android平台软件编程,Xamarin Mono for Android上手快,跨平台共享代码,代价是bug多多,是一味可口的毒药啊!

环境VS2012 + Xamarin Mono Android 4.10.01073

先实现个小功能热热身,建立一个新Android Application工程,修改Activity1.cs代码如下:

using System;

using Android.App;
using Android.Content;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Android.OS;

namespace MyXamarinApp
{
    [Activity(Label = "MyXamarinApp", MainLauncher = true, Icon = "@drawable/icon")]
    public class Activity1 : Activity
    {
        int count = 1;
        DateTime? lastBackKeyDownTime;

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

            // Set our view from the "main" layout resource
            SetContentView(Resource.Layout.Main);

            // Get our button from the layout resource,
            // and attach an event to it
            Button button = FindViewById<Button>(Resource.Id.MyButton);

            button.Click += delegate { button.Text = string.Format("{0} clicks!", count++); };
        }

        public override bool OnKeyDown(Keycode keyCode, KeyEvent e)
        {
            if (keyCode == Keycode.Back && e.Action == KeyEventActions.Down)
            {
                if (!lastBackKeyDownTime.HasValue || DateTime.Now - lastBackKeyDownTime.Value > new TimeSpan(0, 0, 2))
                {
                    Toast.MakeText(this.ApplicationContext, "再按一次退出程序", ToastLength.Short).Show();
                    lastBackKeyDownTime = DateTime.Now;
                }
                else
                {
                    Finish();
                }
                return true;
            }
            return base.OnKeyDown(keyCode, e);
        }
    }
}

功能很简单,就不解释了。请参照:http://www.cnblogs.com/weizilong/archive/2013/08/15/3259452.html

posted on 2014-01-17 17:02  jlzhou  阅读(3894)  评论(0编辑  收藏  举报

导航