Friday, June 5, 2015

// //

How to Create a Pop-Up Menu in android


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

public class MainActivity extends Activity implements OnClickListener{
 Button popup;
 int selected =0;
 int temp;String text="";

 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);
  popup = (Button) findViewById(R.id.popup);
  popup.setOnClickListener(this);
 }

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

 @Override
 public void onClick(View v) {
  // TODO Auto-generated method stub
  switch(v.getId()) {
  case R.id.popup: build_popup();break;
  }
 }

 private void build_popup() {
  // TODO Auto-generated method stub
  AlertDialog.Builder builder = new AlertDialog.Builder(this);
  builder.setTitle("Demo Popup");

  builder.setSingleChoiceItems(R.array.arr, selected, new DialogInterface.OnClickListener() {

   @Override
   public void onClick(DialogInterface dialog, int which) {
    // TODO Auto-generated method stub
    temp = which;
   }

 
 
  });

  builder.setPositiveButton("OK",new DialogInterface.OnClickListener() {
 
   @Override
   public void onClick(DialogInterface dialog, int which) {
    // TODO Auto-generated method stub
    selected = temp;
 
    switch(selected) {
 
    case 0:text = "Bad";
    //Toast.makeText(MainActivity.this, "You Select " + text, Toast.LENGTH_LONG).show();
    break;
 
    case 1:text = "Good";break;
 
    case 2:text = "Very Good";break;
 
    case 3:text = "Average";break;
 
    }
    Toast.makeText(MainActivity.this, "You Selected " + text, Toast.LENGTH_LONG).show();
 
   }
  });

  builder.setNegativeButton("Cancel",new DialogInterface.OnClickListener() {
 
   @Override
   public void onClick(DialogInterface dialog, int which) {
    // TODO Auto-generated method stub
   dialog.cancel();
   }
  });

  AlertDialog al =builder.create();
  al.show();
 }

}

The Activity main