2013年4月15日 星期一

[Android] 對話框(dialog)

MainActivity.java
package com.example.alertdialog;
package com.example.alertdialog;

import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.DialogInterface;
import android.view.Menu;

public class MainActivity extends Activity {

 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);
  
  //呼叫對話框
  AlertDialog dialog = getAlertDialog("Hello", "I am a dialog");
  dialog.show();
 }

 @Override
 public boolean onCreateOptionsMenu(Menu menu) {
  // Inflate the menu; this adds items to the action bar if it is present.
  getMenuInflater().inflate(R.menu.activity_main, menu);
  return true;
 }

 //自定一個對話框的方法
 private AlertDialog getAlertDialog(String title, String message) {

  Builder builder = new AlertDialog.Builder(this);
  builder.setTitle(title);
  builder.setMessage(message);
  builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
   public void onClick(DialogInterface dialog, int which) {
    //當按下OK鍵,即結束對話框
    dialog.dismiss();
   }
  });

  return builder.create();
 }
}
結果:

沒有留言:

張貼留言