Tuesday, 20 January 2015

AlertDialog Example







strings.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>

    <string name="app_name">AlertDialog</string>
    <string name="button_finish">Finish</string>

</resources>

activity_main.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"
    tools:context=".MainActivity" >

    <Button
        android:id="@+id/button_finish"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="30dp"
        android:text="@string/button_finish" />

</RelativeLayout>

MainActivity.java

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

public class MainActivity extends Activity {
       private AlertDialog alertDialog;
       private Button button;

       @Override
       protected void onCreate(Bundle savedInstanceState)
       {
          super.onCreate(savedInstanceState);
          setContentView(R.layout.activity_main);
          button=(Button)findViewById(R.id.button_finish);
          button.setOnClickListener(new OnClickListener() {
               
             @Override
             public void onClick(View v) {
               AlertDialog.Builder builder=new 
                    AlertDialog.Builder(MainActivity.this);
               builder.setTitle("Edit");
               builder.setMessage("are sure to edit");
               builder.setPositiveButton("ok",new 
                    FDialogInterface.OnClickListener() {
                  @Override
                  public void onClick(DialogInterface dialog, int which)
                  {
                   Toast.makeText(getApplicationContext(), "If you have to"
                   + " edit\n create custom dialog", Toast.LENGTH_LONG).show();
                         finish();
                  }
               });
               builder.setNegativeButton("cancel",new 
                    DialogInterface.OnClickListener()
               {
                    
                      @Override
                      public void onClick(DialogInterface dialog, int which)
                      {
                             finish();
                      }
               });
               alertDialog=builder.create();
               alertDialog.show();                    
                 }
          });
       }

}




No comments:

Post a Comment