如果用户按下某个活动,我希望我的应用程序退出。以下是该活动的代码。
public class MainActivity extends FragmentActivity implements DenkoListFragment.ListSelectListener {
private SlidingMenu menu;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
displayView(0);
menu = new SlidingMenu(this);
menu.setTouchModeAbove(SlidingMenu.TOUCHMODE_FULLSCREEN);
menu.setShadowWidthRes(R.dimen.shadow_width);
menu.setShadowDrawable(R.drawable.shadow);
menu.setBehindOffsetRes(R.dimen.slidingmenu_offset);
menu.setFadeDegree(0.35f);
menu.attachToActivity(this, SlidingMenu.SLIDING_CONTENT);
menu.setMenu(R.layout.menu_frame);
menu.setSelected(true);
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.menu_frame, new DenkoListFragment())
.commit();
}
private void displayView(int position) {
Fragment fragment = null;
switch (position) {
case 0:
fragment = new MainViewFragment();
break;
case 1:
fragment = new StationViewFragment();
break;
case 2:
fragment = new MapViewFragment();
break;
default:
break;
}
if (fragment != null) {
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.content_frame, fragment).commit();
} else {
}
}
@Override
public void select(int index) {
displayView(index);
menu.showContent();
}
@Override
public void onBackPressed() {
if (menu.isMenuShowing()) {
menu.showContent();
} else {
new AlertDialog.Builder(this).setIcon(android.R.drawable.ic_dialog_alert).setTitle("Exit")
.setMessage("Are you sure you want to exit?")
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
finish();
System.exit(0);
}
}).setNegativeButton("No", null).show();
}
}
}
需要应用程序两次按下(和两次确认)才能退出。是什么解释了这种行为,有什么方法可以解决这个问题吗?
答案 0 :(得分:0)
从onBackPress()
方法中删除以下代码段。它仅由SlideMenu
处理。
if (menu.isMenuShowing()) {
menu.showContent();
}
来自SlidingFragmentActivity
来电onBackPress
的代码:
@Override
public boolean onKeyUp(int keyCode, KeyEvent event) {
boolean b = mHelper.onKeyUp(keyCode, event);
if (b) return b;
return super.onKeyUp(keyCode, event);
}
mHelper.onKeyUp(keyCode, event)
会调用SlidingActivityHelper
的方法:
public boolean onKeyUp(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK && mSlidingMenu.isMenuShowing()) {
showContent(); //Close the SlidingMenu and show the content view.
return true;
}
return false;
}
答案 1 :(得分:0)
super.onBackPressed();
会按照您的要求执行操作,只需包含super.onBackPressed();
而不是System.exit(0);
,因为它会调用onBackpressed
的{{1}}方法。所以, Activity
方法正确接听电话。
onDestroy