To Examples

ChangeColors Example

Goal:

Directions:

  1. Change the layout to a LinearLayout.
  2. Set the layout height to "wrap_content".
  3. Set the layout width to "match_parent".
  4. Add padding to the linear layout of size
  5. Add a TextView widget to the linear layout.
  6. Add an onClick event handler to the TextView.
  7. Set the text of the button to "Change BgColor".
  8. Set the id of the linear layout to "@+id/layout".
  9. Run the app to check the layout.
  10. Copy this astronomical nebula image nebula.jpg into the drawable folder.
  11. Set this nebula image as the background image:
    android:background="@drawable/nebula
    
  12. Run the app. Here is the layout so far:
        activity_main.xml
  13. Add the colors lightBlue, lightGreen, and lightPink with hex values "#c0ffc0", "#c0ffc0", "#c0ffc0", respectively. Here is the resulting colors file:
        colors.xml
  14. Add the private instance variable colorCode to the top of the MainActivity class; initialize it to 0.
  15. Add this event handler to the MainActivity.java file:
    private int colorCode = 0;
    
  16. Add this event handler to the bottom of the MainActivity class.
    protected void onClick(View view) {
        LinearLayout layout = (LinearLayout) findViewById(R.id.layout);
        colorCode = (colorCode + 1) % 3;
        if (colorCode == 1) {
            layout.setBackgroundColor(getResources( ).getColor(R.color.lightBlue));
        }
        else if (colorCode == 2)  {
            layout.setBackgroundColor(getResources( ).getColor(R.color.lightPink));
        }
        else {
            layout.setBackgroundColor(getResources( ).getColor(R.color.lightGreen));
        }
    }
    
  17. Run your app to test it. Here is the Java activity file:
         MainActivity.java