Android UI Interaction with Java and Resource Management
The R Class and Android Resource Management
- The R class is a central, automatically generated class within an Android project that is created when the application is compiled. It acts as a global variable or a mapping index that provides access to all resources located in the res directory.
- Resources are categorized into subclasses within the R class according to their directory type. Examples include:
R.drawable: Accesses image and graphic resources.R.layout: Accesses XML layout files.R.string: Accesses string values defined in XML.R.id: Accesses specific view IDs assigned within layout files.R.color: Accesses color definitions.
- Accessing a resource via the R class (e.g.,
R.drawable.icon) initially returns an integer ID rather than the actual resource object. This integer acts as a pointer that the Android system uses to retrieve the substantive resource. - Retrieval methods for actual resources vary depending on the resource type:
- Layouts: use
getResources().getLayout(int id). - Strings: use
getResources().getString(int id). - Drawables: use
getDrawable(int id).
Accessing Individual Views in Java
- To interact with specific UI elements (views) defined in XML, you must use the
findViewById function, passing in the integer ID from the R.id subclass. - ID Assignment in XML: A view must have an ID defined in its XML attributes to be accessible in Java. The syntax is
android:id="@+id/yourIDName".- The
@ symbol indicates the resource is in the application's namespace. - The
+ symbol is used only when creating a new ID for the first time. - The
/ separates the resource type from the specific name. - Referencing an existing ID (common in RelativeLayout to position one view relative to another) uses the syntax
@id/existingIDName without the plus sign.
- Object Casting: Because
findViewById returns a generic View object, it must be cast to the specific type (e.g., TextView, Button, ImageView) to access type-specific functionality. For example: TextView tv = (TextView) findViewById(R.id.textViewwelcome);. - View Groups: Since view groups (like
LinearLayout or RelativeLayout) are specialized types of views, they can also be retrieved using findViewById and cast accordingly.
Programmatic UI Interaction and Properties
- Once a view object is retrieved in Java, its properties can be modified or read using various functions:
- TextView: Use
setText(), setTextColor(), or setAllCaps(). - ImageView: Change images using
setImageDrawable(Drawable drawable). The drawable resource is typically fetched via getDrawable(R.drawable.filename). - EditText: Read input values using
getText(). The return value of getText() is not a string by default and is often converted using .toString(). - Visibility: Modify view visibility using
setVisibility(). Three constants are used for this state:VISIBLE: The view is drawn and takes up space.INVISIBLE: The view is not drawn but still occupies space in the layout.GONE: The view is removed from the screen entirely and takes up no space.
- Focus Management: Use
requestFocus() to move focus to a specific view. Only focusable views (like EditText) can accept focus; calling this on a non-focusable view like a TextView will have no effect.
Event Listeners and Click Handling
- Listeners allow Java code to respond to user events. Examples include
onDragListener, onFocusChangeListener, and onKeyListener. - setOnClickListener: This function sets a listener that triggers when a user clicks a view. The programmatic pattern involves:
- Calling
setOnClickListener on the view object. - Passing in a
new View.OnClickListener(). - Overriding the
onClick(View v) method to define the behavior.
- XML vs. Java Listeners: While listeners can be set programmatically, using the
android:onClick attribute in the XML is often considered cleaner for basic interactions. The XML attribute refers directly to a public method in the Activity Java file that takes a View as its single parameter.
Interactive Application Demo: The Summer App
- This demonstration involves creating an application that changes its background and button text upon a user click.
- Resource Setup:
- Colors: New values
coral_dark and coral_light are added to res/values/colors.xml. - Theme Integration: The application theme in
themes.xml is updated using colorPrimary (set to coral), colorPrimaryVariant (set to coral_light), and colorOnPrimary (set to white). - Strings: A string resource
string_start with the value "start" is created in strings.xml. - Images: Two images (
image_blank and image_summer) are added to the res/drawable directory.
- Layout Configuration (activity_main.xml):
- An
ImageView is set to match_parent for width/height with android:scaleType="centerCrop" to fill the screen. It is assigned the ID iv_main. - A
Button with the ID btn_main is centered using constraints and given a margin of 20 dp. Its textAppearance is set to large for readability.
- Java Implementation (MainActivity.java):
- Layout Inflation:
setContentView(R.layout.activity_main) uses the R class to load the initial UI. - Accessing Views:
ImageView imgMain = (ImageView) findViewById(R.id.iv_main); and Button btnMain = (Button) findViewById(R.id.btn_main);. - Updating Properties:
imgMain.setImageDrawable(getDrawable(R.drawable.image_summer)); changes the background.btnMain.setText(getResources().getString(R.string.string_start)); updates the button text.
- Interaction: The code is wrapped in a public method
onClickStart(View v) tied to the XML android:onClick="onClickStart" attribute, ensuring changes only occur after the button is pressed.
Questions & Discussion
- Question: What are the three colors usually added to set a theme?
- Response: The primary colors to set in the theme are
colorPrimary, colorPrimaryVariant, and colorOnPrimary (which determines the color of text/elements drawn on top of the primary color). - Question: How do you avoid the button going all the way to the edges of the screen?
- Response: Apply a margin attribute in the XML, such as
android:layout_margin="20dp", to create space between the view and the parent container boundaries. - Administrative Note: Feedback for class representatives should be submitted via the provided form before the 01:00 deadline today.