Thursday 8 December 2011

Android - Why not use alert dialog instead of spinner?

Spinner in android is more confusing to use. It is also hard to customize it for our needs. Based on the purpose, a simple alert dialog could be used as a replacement for spinner.
In my requirement, I had a button. When the button is clicked, the options should be listed. Based on the selected options, the value of the button is set.
Here is the code for the above requirement.

In the Xml, define the button layout.
<Button
android:id="@+id/annualButton1"
        android:layout_width="50dp"
        android:layout_height="40dp"
        android:layout_toRightOf="@id/totincome"
        android:layout_marginLeft ="10dp"
        android:layout_marginRight="5dp"
        android:layout_alignTop="@id/totincome"
        android:background="@android:drawable/btn_default"
        android:textSize="15dp"/>


In the code, alert dialog is called when the button is clicked.  Based on the option selected, button value is set.

annualButton1.setOnClickListener(new OnClickListener()
{
              public void onClick(View v)
              {
                    sButtonClicked = "button1";
                    showSpinner();
                                   
                }
        });
 
 
protected void showSpinner()
    {
            AlertDialog.Builder b = new Builder(this);
            String[] options = {sItem1,sItem2};
                 
            b.setTitle("Select an option" );
                  b.setSingleChoiceItems(options, -1,new DialogInterface.OnClickListener(){
                        public void onClick(DialogInterface dialog, int which)
                        {
 
                     dialog.dismiss();
                     switch(which){
                     case 0:
                     {
                           annualButton.setText("p.a");;
                           sAnnual = sItem1;
                         break;
                     }
                     case 1:
                     {
                           annualButton.setText("p.m");
                           sAnnual = sItem2;
                         break;
                     }
                                 
                 }}
 
                        });
                  b.setPositiveButton("CANCEL", new DialogInterface.OnClickListener() {
                 public void onClick(DialogInterface dialog, int id) {
                   
                      dialog.dismiss();
                
                      }
             });
                 
                 
                  b.show();}
          
It is much simpler than using a spinner. Isn’t it?

No comments:

Post a Comment