Sunday, March 20, 2011

Alert Dialog with a list of Text and Image options.


I thought this was pretty cool…I used the AlertDialog.Builder, an ArrayAdapter along with the View Holder Android UI pattern to build an AlertDialog containing a list of choices with images for each entry.
Here’s a screen shot from the emulator of my dog/cat/bird selection AlertDialog.
By using a simple TextView as the widget in the animal_row.xml layout file for the ArrayAdapter the image comes for free as the compound drawable.  Each row in the selection list is defined by a POJO holding the string to display, the image and the value to get when if the selection is chosen.  Hopefully the rest of the code is documented well enough to understand.  I would change the code a bit for performance by defining the AlertDialog in onCreate() then calling dialog.show() when the button is pressed.

public class HelloWorld extends Activity
{
    private static final String TAG = "HelloWorld";
    Animal[] _animals;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        loadAnimals();
    }

    /**
     * Create all the choices for the list
     */
 private void loadAnimals() {
  _animals = new Animal[3];

  // define the display string, the image, and the value to use
  // when the choice is selected
  _animals[0]  = new Animal( getString( R.string.dog ),
                         getImg( R.drawable.dog ),
           getString( R.string.dog_val ) );
  _animals[1]  = new Animal( getString( R.string.cat ),
           getImg( R.drawable.cat ),
           getString( R.string.cat_val ) );
  _animals[2]  = new Animal( getString( R.string.bird ),
           getImg( R.drawable.bird ),
           getString( R.string.bird_val ) );
 }

 private Drawable getImg( int res )
 {
  Drawable img = getResources().getDrawable( res );
  img.setBounds( 0, 0, 48, 48 );
  return img;
 }
 /**
  * Handle the event to display the AlertDialog with the list
  */
    public void handlePush( View target ) {
     // define the list adapter with the choices
  ListAdapter adapter = new AnimalAdapter( this, _animals );

  final AlertDialog.Builder ad = new AlertDialog.Builder(this);
  // define the alert dialog with the choices and the action to take
  // when one of the choices is selected
  ad.setSingleChoiceItems( adapter, -1, new OnClickListener() {
   @Override
   public void onClick(DialogInterface dialog, int which) {
    // a choice has been made!
    String selectedVal = _animals[which].getVal();
    Log.d(TAG, "chosen " + selectedVal );
    dialog.dismiss();
   }
  });
  ad.show();
    }

    /**
     * Definition of the list adapter...uses the View Holder pattern to
     * optimize performance.
     */
 static class AnimalAdapter extends ArrayAdapter {

  private static final int RESOURCE = R.layout.animal_row;
  private LayoutInflater inflater;

     static class ViewHolder {
         TextView nameTxVw;
     }

  public AnimalAdapter(Context context, Animal[] objects)
  {
   super(context, RESOURCE, objects);
   inflater = LayoutInflater.from(context);
  }

  @Override
  public View getView(int position, View convertView, ViewGroup parent)
  {
   ViewHolder holder;

   if ( convertView == null ) {
    // inflate a new view and setup the view holder for future use
    convertView = inflater.inflate( RESOURCE, null );

    holder = new ViewHolder();
    holder.nameTxVw =
     (TextView) convertView.findViewById(R.id.animal_name_txtvw);
    convertView.setTag( holder );
   }  else {
    // view already defined, retrieve view holder
    holder = (ViewHolder) convertView.getTag();
   }

   Animal cat = getItem( position );
   if ( cat == null ) {
    Log.e( TAG, “Invalid category for position: ” + position );
   }
   holder.nameTxVw.setText( cat.getName() );
   holder.nameTxVw.setCompoundDrawables( cat.getImg(), null, null, null );

   return convertView;
  }
 }

 /**
  * POJO for holding each list choice
  *
  */
 class Animal {
  private String   _name;
  private Drawable _img;
  private String   _val;

  public Animal( String name, Drawable img, String val ) {
   _name = name;
   _img = img;
   _val = val;
  }

  public String getName() {
   return _name;
  }

  public Drawable getImg() {
   return _img;
  }

  public String getVal() {
   return _val;
  }
 }
}
dog icon from Mac OS X iChat icons


28 comments:

  1. Very useful for me. thanks you

    ReplyDelete
  2. This comment has been removed by the author.

    ReplyDelete
  3. Thank you for allowing me to read it, welcome to the next in a recent article. And thanks for sharing the nice article, keep posting or updating news article.

    java training in marathahalli | java training in btm layout

    java training in jayanagar | java training in electronic city

    java training in chennai | java training in USA

    selenium training in chennai

    ReplyDelete
  4. Excellent blog, I wish to share your post with my folks circle. It’s really helped me a lot, so keep sharing post like this
    python training in tambaram
    python training in annanagar
    python training in OMR
    python training in chennai

    ReplyDelete
  5. Thank you for allowing me to read it, welcome to the next in a recent article. And thanks for sharing the nice article, keep posting or updating news article.

    Blueprism training in Chennai

    Blueprism training in Bangalore

    Blueprism training in Pune

    ReplyDelete
  6. I recently came across your blog and have been reading along. I thought I would leave my first comment.

    python training in rajajinagar | Python training in btm | Python training in usa

    ReplyDelete
  7. Thanks for the good words! Really appreciated. Great post. I’ve been commenting a lot on a few blogs recently, but I hadn’t thought about my approach until you brought it up. 
    devops online training

    aws online training

    data science with python online training

    data science online training

    rpa online training

    ReplyDelete
  8. Very interesting blog. Many blogs I see these days do not really provide anything that attracts others, but believe me the way you interact is literally awesome. I will instantly grab your rss feed to stay informed of any updates you make and as well take the advantage to share some latest information about

    CREDIT CARD HACK SOFTWARE which many are not yet informed of, the recent technology.

    Thank so much for the great job.

    ReplyDelete
  9. Learn Amazon Web Services for making your career as a shining sun with Infycle Technologies. Infycle Technologies is the best AWS training centre in Chennai, providing complete hands-on practical training of professional specialists in the field. In addition to that, it also offers numerous programming language tutors in the software industry such as Python, AWS, Hadoop, etc. Once after the training, interviews will be arranged for the candidates, so that, they can set their career without any struggle. Of all that, 200% placement assurance will be given here. To have the best career, call 7502633633 to Infycle Technologies and grab a free demo to know more.AWS training centre in Chennai

    ReplyDelete
  10. Are you looking for Big Data training in Chennai with placement opportunities? Then we, Infycle Technologies are with you to make your dream into reality. Infycle Technologies is one of the best Big Data Training Institute in Chennai, which offers various programs along with Big Data such as Oracle, Java, AWS, Hadoop, etc., in complete hands-on practical training with trainers, those are specialists in the field. In addition to the training, the mock interviews will be arranged for the candidates, so that they can face the interviews with the best knowledge. Of all that, 100% placement assurance will be given here. To have the words above in the real world, call 7502633633 to Infycle Technologies and grab a free demo to know more.

    https://infycletechnologies.com/big-data-training-in-chennai/

    ReplyDelete
  11. Grab Big Data Course in Chennai for making your career as a shining sun with Infycle Technologies. Infycle Technologies is the best software training center in Chennai, providing complete hands-on practical training of professional specialists in the field. It also offers numerous courses in the IT industry such as Oracle, Java, Python, AWS, Hadoop, etc. Once after the training, interviews will be arranged for the candidates, so that, they can set their career without any struggle. Of all that, 200% placement assurance will be given here. To have the best career, call 7502633633 to Infycle Technologies and grab a free demo to know more.

    https://infycletechnologies.com/big-data-training-in-chennai/

    ReplyDelete
  12. If AWS is a job that you're dreaming of, then we, Infycle are with you to make your dream into reality. Infycle Technologies offers the best AWS Training in Chennai, with various levels of highly demanded software courses such as Oracle, Java, Python, Hadoop, Big Data, etc., in 100% hands-on practical training with specialized tutors in the field. Along with that, the pre-interviews will be given for the candidates, so that, they can face the interviews with complete knowledge. To know more, dial 7502633633 for more.

    ReplyDelete
  13. If AWS is a job that you're dreaming of, then we, Infycle are with you to make your dream into reality. Infycle Technologies offers the best AWS Training in Chennai, with various levels of highly demanded software courses such as Oracle, Java, Python, Hadoop, Big Data, etc., in 100% hands-on practical training with specialized tutors in the field. Along with that, the pre-interviews will be given for the candidates, so that, they can face the interviews with complete knowledge. To know more, dial 7502633633 for more.
    best python course in Chennai

    ReplyDelete
  14. Python Training in Chennai | Infycle Technologies

    If Python is a work you've always wanted, we at Infycle are here to help you make it a reality. Infycle Technologies provides Python Training in Chennai, with various levels of highly sought-after software courses such as Oracle, Java, Python, Big Data, and others, delivered through 100% hands-on practical training with industry experts. In addition, mock interviews will be conducted. For more details contact 7502633633 to grab a free demo.
    best training center in Chennai

    ReplyDelete
  15. If you are dreaming of an IT job !!! Then AWS Course in Chennai!!Is the best choice for you. Yes, what you heard is Right Infycle offering you an AWS course for an Affordable price with experienced trainees, Practical Classes, Flexible timing, and more.

    ReplyDelete
  16. It is extremely nice to see the greatest details presented in an easy and understanding manner.
    full stack web development course malaysia

    ReplyDelete