To Examples

ShowSuit Example

Goal

Directions

  1. Create an Android Studio project named ShowSuit. Leave the layout and activity file with their default names activity_main.xml and MainActivity.java.
  2. If you wish, change the layout to LinearLayout and the orientation attribute to vertical.
  3. Download and unzip the zip file suit-images.zip. Copy the club.png, diamond.png, heart.png, and club.png images into the app/src/main/res/drawable folder.
  4. Drag a RadioGroup widget from the Buttons tab of the Palette.  Drag four radio buttons from the Palette onto the RadioGroup in the Component Tree.
  5. Also drag ImageList and Button widgets onto the layout.
  6. Change the id and text properties of the widgets:

    Widget Type   id    text
    RadioButton rad_club Club
    RadioButton rad_diamond Diamond
    RadioButton rad_heart Heart
    RadioButton rad_spade Spade
    ImageView img_suit  
    Button   Show Image
  7. Add this attribute to the layout file:
    android:scaleType="fitXY"
    
    This stretches the image so that it fills the entire ImageView widget up to the padding, or up to the border if there is no padding.
  8. Add this attribute to the image view:
    <a href="android:background=#ffff00">
    
    This is so we can see where the image view is positioned and sized in the layout.
  9. Run the project to test it. Here is the layout file: activity_main.xml.
  10. Add an onClick attribute to the button with value onClick. This attribute is included in Item 9.
  11. Add this onClick event handler to the MainActivity class:
    public void onClick(View view) {
        RadioButton radSpade = (RadioButton) findViewById(R.id.rad_spade);
        RadioButton radHeart = (RadioButton) findViewById(R.id.rad_heart);
        RadioButton radDiamond = (RadioButton) findViewById(R.id.rad_diamond);
        RadioButton radClub = (RadioButton) findViewById(R.id.rad_club);
        ImageView imgSuit = (ImageView) findViewById(R.id.img_suit);
    
        int image = 0;
        if(radSpade.isChecked( )) {
            image = R.drawable.spade;
        }
        else if(radHeart.isChecked( )) {
            image = R.drawable.heart;
        }
        else if(radDiamond.isChecked( )) {
            image = R.drawable.diamond;
        }
        else if(radClub.isChecked( )) {
            image = R.drawable.club;
        }
        imgSuit.setImageResource(image);
    }
    
  12. Run the app to test it. Here is the MainActivity.java source code file.