我有活动' A'活动' B'活动' C'活动' D'活动' E',活动' E' 。我想退出Activity点击onBackPressed()。当我运行应用程序时,它会转到活动' A'它不会退出应用程序。我该如何实现呢?
这是我的代码
public class MainActivity extends Activity {
TableLayout table_layout;
EditText firstname_et, lastname_et;
Button addmem_btn;
DatabaseHelper databaseHelper = new DatabaseHelper(this);
protected SQLiteDatabase db;
ProgressDialog PD;
ImageView imgButtonBack;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.performance_report);
table_layout = (TableLayout) findViewById(R.id.tableLayout_PerformanceReport);
//ImageView imgButtonBack;
imgButtonBack = (ImageView)findViewById(R.id.imagBackButton);
imgButtonBack.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent i = new Intent(MainActivity.this, Employee_List.class);
i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
//finish();
}
});
}
}
@Override
public void onBackPressed()
{
AlertDialog.Builder alertbox = new AlertDialog.Builder(MainActivity.this);
alertbox.setTitle("Do you wish to exit ?");
alertbox.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface arg0, int arg1) {
// finish used for destroyed activity
finish();
}
});
alertbox.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface arg0, int arg1) {
// Nothing will be happened when clicked on no button
// of Dialog
}
});
alertbox.show();
}
}
感谢Appreciate。
答案 0 :(得分:3)
您可以在onBackPressed
:
@Override
public void onBackPressed() {
// TODO Auto-generated method stub
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
退出应用程序。对我来说工作正常。希望它有所帮助。
答案 1 :(得分:0)
在您打开新活动时调用this.finish()
(从活动A到其他活动)。在你的情况下写这个
public void onClick(View v) {
// TODO Auto-generated method stub
Intent i = new Intent(MainActivity.this, Employee_List.class);
i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
MainActivity.this.finish();
}
});
答案 2 :(得分:0)
你可以这样做 -
private exit = false;
public void onBackPressed() {
if (exit)
Home.this.finish();
else {
Toast.makeText(this, "Press Back again to Exit.",
Toast.LENGTH_SHORT).show();
exit = true;
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
exit = false;
}
}, 3 * 1000);
}
}