User Interface Overview


  • Create a simple user interface with text and buttons
  • Write code for then a user presses a button
  • Access and change the text of objects in the user interface
  • After this section you should know about
    • TextView, setText, Button, onClick, Toast

Separating views from controllers

  • User Interface in fragment_main.xml
  • Button click in fragment_main.xml ends up as call to method in
  • Controller code in
  • Compare to how web pages work
    • User interface in HTML <=> Layout and View XML in fragment_main.xml
    • JavaScript in js-files or inline in web page <=> Java in


  • Recommend to use LinearLayout as root
    <LinearLayout android:orientation="vertical"
  • android:orientation
    • horizontal, where all views inside are displayed next to each other
    • vertical, where all views inside are displayed below each other
  • Views inside of LinearLayout start and end tags
  • android:layout_width, android:layout_height
    • match_parent, means to fill the parent's area regardless of actual size
    • wrap_content, means only to take the space that is needed from actual size
  • Explained further in next chapter

Views in a layout

  • TextView
    • Simple text content
    • android:text is the content
  • Button
    • Button that can be pressed
    • android:onClick is name of Activity method to call when pressed
    • Method can have any valid Java name, but must be void and take View argument
      public void onButton(View source)

Access to a View from Java code

  • You often need to change Views after they've been loaded from XML
  • Give the View an id in the xml layout file
    <TextView android:id="@+id/title"
  • Declare an object in your class of same same as View
    TextView _someAppTitle;
  • Set object to refer to the View in onCreate using findViewById

Use a reference to a View

  • Change the text of a TextView
    _someAppTitle.setText("Now my title is different");
  • Most attributes in the xml have corresponding set-methods for changing them from Java
    • However, some are a bit more difficult to set/change (like android:layout_width)


  • Nothing you eat or drink
    • Android's name for a short text message that appears on top of the user interface and is automatically removed after a few seconds
  • Good feature for notification messages
    • Can also be used for simpler debugging purposes, like checking a value or ensuring a code statement is reached (without using the full debugging capabilities of Eclipse)
  • Show a toast message
    Toast.makeText(this, "Hello, world!", Toast.LENGTH_LONG).show();

More information

  • Book references
    • The Busy Coder's Guide 3.7
      • Using XML based layouts, page 69
      • Employing basic widgets, page 77