Android Tips, Techniques and Theory

PART 2: Creating Content with Java with Android Studio (Programming required)

With Simple Recipes

Go Back To TOC

Program Views

Once you create views either using XML or in Java, you can then use a set of getters and setters to “get” or “set” properties of views. You can also set up event listeners for them.
NOTE: You can also set many component properties in the XML file using attributes (e.g., textColor:#FF0000).

Common View Properties

Most methods use the prefixes “get” or “set” to:

EXAMPLES:

TIP: After typing “set” or “get” on a component (e.g., myComponent.set), you can select the correct method you need from the list. To bring up the list is it is gone, type CTRL+SPACEBAR on Windows or Mac (or Linux). You can also use the following references to get more information about a method:

Display Data From A View

Data can be collected from a view (e.g., EditView) and displayed in another component (e.g., SnackBar or Toast).

EXAMPLE: Displaying User Input in SnackBar

  1. Create a new project using the Basic template that has a FAB (Floating Action Bar) and name it CollectingAndDisplayingApp.
  2. Delete the TextView with the phrase “Hello, World!”
  3. Drag-and-drop a Plain Text component the the top/center of the screen.
  4. In the Properties panel, change the layout_width property to match_parent and the text property to Enter Some Text.
  5. In the MainActivity class within the fab setOnClickListener, add the following highlighted code:

    fab.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
            EditText edittext = (EditText) findViewById(R.id.editText);
    // Collect value that user typed into the EcitText field
    String textEntered = edittext.getText().toString();
            Snackbar.make(view, "You entered " + textEntered, Snackbar.LENGTH_LONG)
    .setAction("Action", null).show();
    }
    });

    NOTE: The getText() method actual return an editable text object and not the actual text. To get the actual text you used the .toString() method. This is akin to casting an HTML input field which is a string into a number using the Number() method (e.g., Number(myTextField)).

  6. CHECK POINT: Run the app in an emulator and type some text into the input text field and then press the FAB button. You should see that the text you entered into the input text field gets displayed in the SnackBar.

    SEE ANDROID APP: CollectingAndDisplayingApp