To Examples

MonthButtons1 Example

Goal

Directions

  1. Create a project named MonthButtons1.  Leave the layout and activity files with their default names.
  2. Copy the 12 month icon files in month-icons.zip into the drawable folder:
    app/src/main/res/drawable
    
  3. Change the layout to LinearLayout and place it in a ScrollView like this:
    <ScrollView
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context=".MainActivity">
    
       <LinearLayout
           android:layout_width="match_parent"
           android:layout_height="match_parent"
           android:orientation="vertical">
       </LinearLayout>
    </ScrollView>
    
  4. Add a month button to the layout:
    <Button
        android:layout_margin="20dp"
        android:layout_width="200dp"
        android:layout_height="100dp"
        android:text="January"
        android:onClick="onClick"
        android:drawableLeft="@drawable/january"
    
  5. Run your app to test it.
  6. Add this event handler to the activity code:
     public void onClick(View view) {
        Button btn = (Button) view;
        String text = btn.getText( ).toString( ) + " button clicked.";
        int duration = Toast.LENGTH_LONG;
        Toast toast = Toast.makeText(this, text, duration);
        toast.show( );
    }
    
  7. Run the app again to test it.
  8. Copy the button 11 more times for the other months. Change the text and the image to match the month of each button.
  9. Test the app again. Here is the emulator screenshot.
  10. Here are the final files for the layout and activity:
        activity_main.xml   MainActivity.java