Java reference to XML object

The attribute

android:id="@+id/textview"
of the TextView in the main.xml file creates a static int named R.id.textview in the R.java file. See ID for the @+ in the id. The method findViewById in the Activity in ReferenceActivity.java takes the variable R.id.textview as an argument and returns a reference to some type of View. The reference must be cast into a reference to a TextView before it can be stored in a TextView variable.

findViewById cannot be called before setContentView.

Source code in Reference.zip

Remember to add the android:id attribute to the TextView in main.xml, and the import for class Toast in ReferenceActivity.java.

  1. ReferenceActivity.java
  2. main.xml
  3. R.java

Things to try

  1. Display more information about the TextView.
    	Toast.makeText(this, "textView.getTextSize() == " + textView.getTextSize(),
    		Toast.LENGTH_LONG).show();
    
    textView.getTextSize() == 21.0
    
    Colors are conventionally printed in hexadecimal. A shade of gray has equal amounts of red, green, and blue. The alpha comes first.
    	Toast.makeText(this, "textView.getCurrentTextColor() == "
    		+ String.format("%08X", textView.getCurrentTextColor()),
    		Toast.LENGTH_LONG).show();
    
    textView.getCurrentTextColor() == FFBEBEBE
    
  2. Change the attributes of the TextView.
    	textView.setText("Your message here.");