To Examples

MonthButtons2 Example

Goal

Directions

  1. Create a project named MonthButtons2.  Leave the layout and activity files with their default names.
  2. 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>
    
  3. Add the id linear_layout to the linear layout:
    android:id="@+id/linear_layout"
    
  4. Add this code to OnCreate method of the activity code file:
     // The layout and buttons are declared as 
    // final because they are referenced in the
    // event handler in the inner class.
    final LinearLayout layout = (LinearLayout)
    findViewById(R.id.linear_layout);
    LinearLayout.LayoutParams params =
        new LinearLayout.LayoutParams(
            LayoutParams.MATCH_PARENT,
            LayoutParams.MATCH_PARENT);
    
    //CharSequence[ ] months = {
    String[ ] months = {
        "January ", "February", "March ", "April ", "May ", 
        "June ", "July ", "August ", "September",
        "October ", "November", "December "};
    
    for (int i = 1; i <= 12; i++) {
        final Button btn = new Button(this);
        btn.setId(i);
        btn.setText(months[i - 1]);
        btn.setLayoutParams(params);
        layout.addView(btn);
    }
  5. Run your app to test it.
  6. Add this code at the end of the for loop to add event handlers to all of the buttons.
    btn.setOnClickListener(new View.OnClickListener( ) {
        public void onClick(View v) {
            Button b =(Button) v;
            String label = b.getText( ).toString( );
            System.out.println("Text: " + label);
            Toast toast = Toast.makeText(
                getApplicationContext(),
                "Clicked Button:" + label,
                Toast.LENGTH_LONG);
            toast.show( );
        }
    });
    
  7. Run the app again to test it. Here is the emulator screenshot.
  8. Here are the final files for the layout and activity:
        activity_main.xml   MainActivity.java