隐藏

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

发布:2015/5/25 8:43:22作者:管理员 来源:本站 浏览次数:1121

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

环境VS2012 + Xamarin Mono Android 4.10.01073

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
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