1 public class MainActivity extends Activity { 2 3 @Override 4 protected void onCreate(Bundle savedInstanceState) { 5 super.onCreate(savedInstanceState); 6 setContentView(R.layout.activity_main); 7 8 } 9 10 long startTime; 11 12 @Override 13 public void onBackPressed() { 14 if (System.currentTimeMillis() - startTime < 2000) { 15 super.onBackPressed(); 16 } else { 17 startTime = System.currentTimeMillis(); 18 19 Toast toast = new Toast(this); 20 21 LinearLayout layout = new LinearLayout(this); 22 layout.setOrientation(LinearLayout.VERTICAL); 23 layout.setBackgroundColor(Color.YELLOW); 24 25 TextView tv1 = new TextView(this); 26 tv1.setText("提示"); 27 tv1.setGravity(Gravity.CENTER); 28 29 TextView tv2 = new TextView(this); 30 tv2.setText("再按一次Back键退出"); 31 tv2.setGravity(Gravity.CENTER); 32 33 layout.addView(tv1); 34 layout.addView(tv2); 35 36 toast.setView(layout); 37 toast.setGravity(Gravity.CENTER_VERTICAL | Gravity.FILL_HORIZONTAL, 0, -200); 38 toast.setDuration(Toast.LENGTH_SHORT); 39 toast.show(); 40 41 } 42 43 } 44 45 }