如何使用对话框结束活动

时间:2014-05-02 14:12:52

标签: android android-activity dialog

我正在编写一个简单的游戏,现在,我希望我的应用程序在倒计时结束时显示一个对话框。我尝试了该代码(见下文),但它不起作用:

protected void alertbox()
   {
   new AlertDialog.Builder(this)
      .setMessage("You've scored " + score + " points!")
      .setTitle("Congatulations!")
      .setCancelable(false)
      .setNeutralButton(android.R.string.cancel,
         new DialogInterface.OnClickListener() {
         public void onClick(DialogInterface dialog, int whichButton){}
         ButtonActivity.this.finish();
         })
      .show();
   }

3 个答案:

答案 0 :(得分:1)

试试这个:

new AlertDialog.Builder(context).setMessage("Congratulations! You scored " + score + " points!")
.setPositiveButton("Ok", new DialogInterface.OnClickListener()
{
    @Override
    public void onClick(DialogInterface dialog, int which)
    {
        finish();
    }
}).show();

答案 1 :(得分:1)

这样做:

    final Dialog dialog = new Dialog(ButtonActivity.this);
    dialog.setContentView(R.layout.dialog);
    dialog.setTitle("Dialog Title");
    TextView text = (TextView) dialog.findViewById(R.id.text);
    text.setText("Congratulations! You scored " + score + " points!");
    Button dialogButton = (Button) dialog.findViewById(R.id.dialogButtonOK);

    dialogButton.setOnClickListener(new OnClickListener() {
       @Override
       public void onClick(View v) {
        dialog.dismiss();
        ButtonActivity.this.finish();
       }
    });
    dialog.show();

dialog.xml:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >



    <TextView
        android:id="@+id/text"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:textColor="#FFF" 
        />

     <Button
        android:id="@+id/dialogButtonOK"
        android:layout_width="100px"
        android:layout_height="wrap_content"
        android:text="Ok"
        android:layout_marginTop="5dp"
        android:layout_marginRight="5dp"
        android:layout_below="@+id/text"
        />

</RelativeLayout>

答案 2 :(得分:0)

protected void alertbox(){
    new AlertDialog.Builder(this)
  .setMessage("You've scored " + score + " points!")
  .setTitle("Congatulations!")
  .setCancelable(false)
  .setNeutralButton(android.R.string.cancel,
     new DialogInterface.OnClickListener() {
     public void onClick(DialogInterface dialog, int whichButton){
         Intent intent =new Intent(getApplicationContext(), NextActivityClassName.class);
         intent.putExtra("ID",score);
         startActivity(intent);
         finish();
     }
  }).show();

}

在下一个活动中使用:

 int scoreValue= getIntent().getIntExtra("ID", defaultValueIntValue);