Android Toast 提示按两次返回键退出

时间:2024-06-30 18:36:50
 public class MainActivity extends Activity {

     @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main); } long startTime; @Override
public void onBackPressed() {
if (System.currentTimeMillis() - startTime < 2000) {
super.onBackPressed();
} else {
startTime = System.currentTimeMillis(); Toast toast = new Toast(this); LinearLayout layout = new LinearLayout(this);
layout.setOrientation(LinearLayout.VERTICAL);
layout.setBackgroundColor(Color.YELLOW); TextView tv1 = new TextView(this);
tv1.setText("提示");
tv1.setGravity(Gravity.CENTER); TextView tv2 = new TextView(this);
tv2.setText("再按一次Back键退出");
tv2.setGravity(Gravity.CENTER); layout.addView(tv1);
layout.addView(tv2); toast.setView(layout);
toast.setGravity(Gravity.CENTER_VERTICAL | Gravity.FILL_HORIZONTAL, 0, -200);
toast.setDuration(Toast.LENGTH_SHORT);
toast.show(); } } }

MainActivity

Android Toast  提示按两次返回键退出