美好的一天。我有一个问题,我在点击一个按钮时显示一个消息框。消息框简单显示注册确认。之后我打开一个新活动。 问题是它显示了消息框,然后在不等待单击确定按钮的情况下启动新活动。如何在单击确定按钮时显示新活动。
以下是我使用的代码。
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.register);
Button btn = (Button)findViewById(R.id.registerButton);
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(getApplicationContext(), BookingActivity.class);
AlertDialog.Builder dlgAlert = new AlertDialog.Builder(context);
dlgAlert.setMessage("You have successfully Registered.Please Press okay to continue");
dlgAlert.setTitle("Registration");
dlgAlert.setPositiveButton("OK", null);
dlgAlert.setCancelable(false);
dlgAlert.create().show();
startActivity(intent);
finish();
}
});
将代码更改为
@Override
public void onClick(View view) {
// Intent intent = new Intent(getApplicationContext(), BookingActivity.class);
AlertDialog.Builder dlgAlert = new AlertDialog.Builder(context);
dlgAlert.setMessage("You have successfully Registered.Please Press okay to continue");
dlgAlert.setTitle("Registration");
dlgAlert.setPositiveButton(R.string.button_ok, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
Intent intent = new Intent(getApplicationContext(), BookingActivity.class);
startActivity(intent);
}
});
dlgAlert.setCancelable(false);
dlgAlert.show();
答案 0 :(得分:1)
不要在那里开始活动。删除行startActivity(intent)
和finish()
。你需要这样做
builder.setPositiveButton(R.string.label_ok, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
Intent intent = new Intent(your arguments here)
startActivity(intent);
}
});
builder.show();
所以您需要做的就是将行更改为setPositiveButton
并使用上面给出的。
根据您的风格,您不是在对话框中设置操作,而是在显示对话框的按钮上设置操作。
答案 1 :(得分:1)
试试这个
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.register);
Button btn = (Button)findViewById(R.id.registerButton);
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
AlertDialog.Builder dlgAlert = new AlertDialog.Builder(context);
dlgAlert.setMessage("You have successfully Registered.Please Press okay to continue");
dlgAlert.setTitle("Registration");
dlgAlert.setPositiveButton("OK", null);
dlgAlert.setCancelable(false);
dlgAlert.create().show();
dlgAlert.setPositiveButton(R.string.dialog_ok, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
Intent intent = new Intent(getApplicationContext(), BookingActivity.class);
startActivity(intent);
}
});
}
});