Skip to content
Search

Android:Example

lastmod 2024-11-29created 2016-12-093 edits

Tips & Examples related to Android.

Examples

How to get a widget instance

Notes on how to get the instance of a widget control defined in an Activity's Layout XML. Below explains how to get the instance of a TextView. First, the widget must be given an ID. So open the layout XML and add an ID as below.

<TextView
android:id="@+id/TextViewIdName"/>

Add the ID with the android:id attribute, writing the ID name after @+id/. In the case above, TextViewIdName is the ID.) The added ID is automatically added as a property of the R.java class under the gen directory. Then, inside the activity for that layout, you can get the instance with findViewById() as below.

TextView text_view_object = (TextView) findViewById(R.id.TextViewIdName);

Simple way to add a button click event

A simple way to implement the click event of a Button widget defined in an Activity's Layout XML is as follows. First, use the android:onClick attribute in the Layout and write the name of the Method that will actually be implemented in the activity.

<Button
android:onClick="onClickEvent"/>

Then add the method inside the activity for that layout.

public void onClickEvent(View v) {
  // ...
}

See also