2014/05/30

Android Alert Dialog

Code:
package com.cy.myalert;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import android.content.DialogInterface.OnClickListener;

public class MainActivity extends Activity {
 private Button button;

 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);
  button = (Button) findViewById(R.id.button1);
  button.setOnClickListener(new View.OnClickListener() {

   @Override
   public void onClick(View v) {
    AlertDialog.Builder builder = new AlertDialog.Builder(
      MainActivity.this);
    builder.setTitle("Title").setMessage("Hi");
    builder.setNegativeButton("setNegativeButton",
      clickListenerNegative).setPositiveButton(
      "PositiveButton", clickListenerPositive);
    builder.create().show();
   };
  });

 }

 private OnClickListener clickListenerNegative = new OnClickListener() {

  @Override
  public void onClick(DialogInterface dialog, int which) {
   Toast.makeText(getApplicationContext(), "Negative", 0).show();
  }
 };

 private OnClickListener clickListenerPositive = new OnClickListener() {

  @Override
  public void onClick(DialogInterface dialog, int which) {
   Toast.makeText(getApplicationContext(), "Positive", 0).show();
  }
 };
}




XML:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:layout_marginTop="28dp"
        android:text="Button" />

</RelativeLayout>


成果:






參考資料:
http://developer.android.com/guide/topics/ui/dialogs.html#AlertDialog