84669 person learning
152542 person learning
20005 person learning
5487 person learning
7821 person learning
359900 person learning
3350 person learning
180660 person learning
48569 person learning
18603 person learning
40936 person learning
1549 person learning
1183 person learning
32909 person learning
好多程序返回到第一个activity的时候,再按back会弹出吐司提示双击退出程序 在网上查了一下发现都是用keycode来实现的,用onBackPressed能实现同样的效果吗? 两种哪种方式好一点?用java计时器和handle延时发送两种之间哪个好一点?
ringa_lee
It’s not that troublesome, just use toast’s getView().getParent() to determine whether it is empty. API 16 test passed
public class MainActivity extends Activity { private Toast toast; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); toast = Toast.makeText(getApplicationContext(), "确定退出?", 0); } public void onBackPressed() { quitToast(); } /* public boolean onKeyDown(int keyCode, KeyEvent event) { System.out.println(keyCode + "...." + event.getKeyCode()); if(keyCode == KeyEvent.KEYCODE_BACK){ quitToast(); } return super.onKeyDown(keyCode, event); } */ private void quitToast() { if(null == toast.getView().getParent()){ toast.show(); }else{ System.exit(0); } } }
onbackpressed is OK, http://tianmaying.com/snippet/8ab3eda84dd8bc9f014de5eab9bf036c By the way, are you sure there are many programs that use double-click to exit? I can’t say which one is better. I usually use onbackpressed.
/* 上一次按返回按键的时间 */ long preBackPressTime; /* 按返回按键的次数 */ long pressTimes; @Override public void onBackPressed() { super.onBackPressed(); long cBackPressTime = SystemClock.uptimeMillis(); if (cBackPressTime - preBackPressTime < 2000) { pressTimes++; if (pressTimes >= 2) { finish(); } } else { pressTimes = 1; } if (pressTimes == 1) { Toast.makeText(this, "再按一次退出程序", Toast.LENGTH_SHORT).show(); } preBackPressTime = cBackPressTime; }
It’s not that troublesome, just use toast’s getView().getParent() to determine whether it is empty. API 16 test passed
onbackpressed is OK, http://tianmaying.com/snippet/8ab3eda84dd8bc9f014de5eab9bf036c
By the way, are you sure there are many programs that use double-click to exit?
I can’t say which one is better. I usually use onbackpressed.