IF 633
Mobile Application Programming
03 Android Studio User-Interface Components and User-Interaction
REVIEW
▪ Android Activity
▪ Views
▪ Layouts
▪ Relative Layout
▪ Linear Layout
▪ Frame Layout
▪ Constraint Layout
▪ Resources for UI
OBJECTIVES
▪ Explain and define what Text View and scrolling views are
▪ Explain and define what Button and other input control views are
▪ Explain and define what touch gestures are
▪ Explain and introduce what Container is (e.g. Recycle View)
▪ Explain and introduce what App Bar, and Dialogs are.
OUTLINE
▪ Text View, Scrolling View
▪ Button and other input control views
▪ Touch Gesture
▪ Container (e.g. Recycler View)
▪ App Bar and Dialogs.
What is a TextView
▪ One View subclass you may use often is the TextView class, which displays text on the
screen. You can use TextView for a View of any size, from a single character or word to a
full screen of text.
▪ EditText is TextView subclass with editable text
▪ Controlled with layout attributes
▪ Set text:
▪ Statically from string resource in XML
▪ Dynamically from Java code and any source
Formatting text in string resource
▪ Use <b> … </b> and <i> … </i> HTML tags for bold and italics
▪ All other HTML tags are ignored
▪ String resources: one unbroken line = one paragraph
▪ \n starts a new a line or paragraph
▪ Escape apostrophes and quotes with backslash (\", \')
▪ Escape any non-ASCII characters with backslash (\)
Creating TextView in XML
<TextView android:id="@+id/textview"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@string/my_story"/>
<!-- more attributes -->
/>
android:layout_width and android:layout_height are required for a
TextView
Common TextView attributes
android:text—text to display
android:textColor—color of text
android:textAppearance—predefined style or theme
android:textSize—text size in sp (scaled-pixel)
android:textStyle—normal, bold, italic, or bold|italic
android:typeface—normal, sans, serif, or monospace
android:lineSpacingExtra—extra space between lines in sp
Formatting active web links
<string name="article_text">... [Link] ...</string>
<TextView Don’t use HTML for a
android:id="@+id/article“ web link in free-form text
android:layout_width="wrap_content"
android:layout_height="wrap_content"
autoLink values:"web", "email",
android:autoLink="web"
"phone", "map", "all"
android:text="@string/article_text"/>
Creating TextView in Java code
TextView myTextview = new TextView(this);
[Link](LayoutParams.MATCH_PARENT);
[Link](LayoutParams.WRAP_CONTENT);
[Link](3);
[Link]([Link].my_story);
[Link](userComment);
What about large amounts of text?
▪ News stories, articles, etc…
▪ To scroll a TextView, embed it in a ScrollView
▪ Only one View element (usually TextView) allowed in a
ScrollView
▪ To scroll multiple elements, use one ViewGroup (such as
LinearLayout) within the ScrollView
ScrollView for scrolling content
▪ ScrollView is a subclass of FrameLayout
▪ Holds all content in memory
▪ Not good for long texts, complex layouts
▪ Do not nest multiple scrolling views
▪ Use HorizontalScrollView for horizontal scrolling
▪ Use a RecyclerView for lists
ScrollView layout with one TextView
<ScrollView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/article_subheading">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
.../>
</ScrollView>
ScrollView layout with a view group
<ScrollView ...
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:id="@+id/article_subheading"
.../>
<TextView
android:id="@+id/article" ... />
</LinearLayout>
</ScrollView>
ScrollView with image and button
<ScrollView...>
One child of ScrollView
<LinearLayout...> which can be a layout
<ImageView.../>
<Button.../> Children of the layout
<TextView.../>
</LinearLayout>
</ScrollView>
Users expect to interact with apps
▪ Tapping or clicking, typing, using gestures, and talking
▪ Buttons perform actions
▪ Other UI elements enable data input and navigation
User interaction design
Important to be obvious, easy, and consistent:
▪ Think about how users will use your app
▪ Minimize steps
▪ Use UI elements that are easy to access, understand, use
▪ Follow Android best practices
▪ Meet user's expectations
Button
▪ View that responds to tapping (clicking) or pressing
▪ Usually text or visuals indicate what will happen when
tapped
▪ State: normal, focused, disabled, pressed, on/off
Button image assets
1. Right-click app/res/drawable
2. Choose New > Image Asset
3. Choose Action Bar and Tab
Items from drop down menu
4. Click the Clipart: image
(the Android logo) Experiment:
2. Choose New > Vector Asset
Responding to button taps
▪ In your code: Use OnClickListener event listener.
▪ In XML: use android:onClick attribute in the XML layout:
<Button
android:id="@+id/button_send"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/button_send"
android:onClick="sendMessage" /> android:onClick
Setting listener with onClick callback
Button button = findViewById([Link]);
[Link](new [Link]() {
public void onClick(View v) {
// Do something in response to button click
}
});
Floating Action Buttons (FAB)
● Raised, circular, floats above layout
● Primary or "promoted" action for a
screen
● One per screen
For example:
Add Contact button in Contacts app
Using FABs
▪ Start with Basic Activity template
▪ Layout:
<[Link]
android:id="@+id/fab"
android:layout_gravity="bottom|end"
android:layout_margin="@dimen/fab_margin"
android:src="@drawable/ic_fab_chat_button_white"
.../>
FAB size
▪ 56 x 56 dp by default
▪ Set mini size (30 x 40 dp) with app:fabSize attribute:
▪ app:fabSize="mini"
▪ Set to 56 x 56 dp (default):
▪ app:fabSize="normal"
Touch Gestures
Touch gestures include:
▪ long touch
▪ double-tap Don’t depend on touch
▪ fling gestures for app's basic
▪ drag
behavior!
▪ scroll
▪ pinch
Detect gestures
Classes and methods are available to help you handle gestures.
▪ GestureDetectorCompat class for common gestures
▪ MotionEvent class for motion events
GestureDetectorCompat lets you detect common gestures without
processing the individual touch events yourself. It detects various
gestures and events using MotionEvent objects, which report
movements by a finger (or mouse, pen, or trackball).
Creating an instance of GestureDetectorCompat
public class MainActivity extends Activity {
private GestureDetectorCompat mDetector;
@Override
public void onCreate(Bundle savedInstanceState) {
[Link](savedInstanceState);
setContentView([Link].activity_main);
mDetector = new GestureDetectorCompat(this, new
MyGestureListener());
// ... Rest of onCreate code.
}
// ... Rest of code.
}
Gesture Listener
When you instantiate a GestureDetectorCompat object, one of the parameters it takes is a
class that you must create, which is MyGestureListener in the snippet above. The class you
create should do one of the following:
▪ Implement the [Link] interface to detect all standard
gestures, or
▪ Extend the [Link] class, which you can use to
process only a few gestures by overriding the methods you need.
SimpleOnGestureListener provides methods such as onDown(), onLongPress(), onFling(),
onScroll(), and onSingleTapUp().
Implement MyGestureListener
class MyGestureListener extends [Link] {
private static final String DEBUG_TAG = "Gestures";
@Override
public boolean onDown(MotionEvent event) {
Log.d(DEBUG_TAG,"onDown: " + [Link]());
return true;
}
Implement MyGestureListener
@Override
public boolean onFling(MotionEvent event1, MotionEvent event2,
float velocityX, float velocityY) {
Log.d(DEBUG_TAG, "onFling: " +
[Link]()+[Link]());
return true;
}
}
Accepting user input
▪ Freeform text and numbers: EditText (using keyboard)
▪ Providing choices: CheckBox, RadioButton, Spinner
▪ Switching on/off: Toggle, Switch
▪ Choosing value in range of values: SeekBar
Examples of input controls
1. EditText
2. SeekBar
3. CheckBox
4. RadioButton
5. Switch
6. Spinner
View focus
▪ The View that receives user input has "Focus"
▪ Only one View can have focus
▪ Focus makes it unambiguous which View gets the input
▪ Focus is assigned by
▪ User tapping a View
▪ App guiding the user from one text input control to the next
using the Return, Tab, or arrow keys
▪ Calling requestFocus() on any View that is focusable
Guiding focus
▪ Arrange input controls in a layout from left to right and top to
bottom in the order you want focus assigned
▪ Place input controls inside a view group in your layout
▪ Specify ordering in XML
android:id="@+id/top"
android:focusable="true"
android:nextFocusDown="@+id/bottom"
Set focus explicitly
Use methods of the View class to set focus
▪ setFocusable() sets whether a view can have focus
▪ requestFocus() gives focus to a specific view
▪ setOnFocusChangeListener() sets listener for when view gains or
loses focus
▪ onFocusChanged() called when focus on a view changes
EditText for multiple lines of text
▪ EditText default
▪ Alphanumeric keyboard
▪ Suggestions appear
▪ Tapping Return (Enter) key
starts new line
Return
key
Customize with inputType
● Set in Attributes pane of layout editor
● XML code for EditText:
<EditText
android:id="@+id/name_field"
android:inputType =
"textPersonName"
...
Getting text
▪ Get the EditText object for the EditText view
EditText simpleEditText =
findViewById([Link].edit_simple);
▪ Retrieve the CharSequence and convert it to a string
String strValue =
[Link]().toString();
CheckBox
▪ User can select any number of choices
▪ Checking one box does not uncheck
another
▪ Users expect checkboxes in a vertical list
▪ Commonly used with a Submit button
▪ Every CheckBox is a View and can have
an onClick handler
RadioButton
▪ Put RadioButton elements in a RadioGroup
in a vertical list (horizontally if labels are
short)
▪ User can select only one of the choices
▪ Checking one unchecks all others in group
▪ Each RadioButton can have onClick handler
▪ Commonly used with a Submit button for
the RadioGroup
Toggle buttons and switches
▪ User can switch between on and off
▪ Use android:onClick for click handler
Toggle buttons
Switches
What is the App Bar?
Bar at top of each screen—same for all devices (usually)
1. Nav icon to open navigation drawer
2. Title of current Activity
3. Icons for options menu items
4. Action overflow button for
the rest of the options menu
What is the options menu?
▪ Action icons in the
app bar for important
items (1)
▪ Tap the three dots, the
"action overflow button"
to see the options menu (2)
▪ Appears in the right corner of the app bar (3)
▪ For navigating to other activities and editing app settings
Dialogs
▪ Dialog appears on top,
interrupting flow of Activity
▪ Requires user action to dismiss
AlertDialog
TimePickerDialog DatePickerDialog
AlertDialog
AlertDialog can show:
1. Title (optional)
2. Content area
3. Action buttons
Build the AlertDialog
Use [Link] to build alert dialog and set attributes:
public void onClickShowAlert(View view) {
[Link] alertDialog = new
[Link]([Link]);
[Link]("Connect to Provider");
[Link]([Link].alert_message);
// ... Code to set buttons goes here.
Set the button actions
▪ [Link]()
▪ [Link]()
▪ [Link]()
alertDialog code example
[Link](
"OK", [Link]() {
public void onClick(DialogInterface dialog, int which) {
// User clicked OK button.
}
});
Same pattern for setNegativeButton() and setNeutralButton()
What is a RecyclerView?
▪ RecyclerView is scrollable
container for large data sets
▪ Efficient
▪ Uses and reuses limited
number of View elements
▪ Updates changing data fast
RecyclerView Components
▪ Data
▪ RecyclerView scrolling list for list items—RecyclerView
▪ Layout for one item of data—XML file
▪ Layout manager handles the organization of UI components in a
View—[Link]
▪ Adapter connects data to the RecyclerView—[Link]
▪ ViewHolder has view information for displaying one item—
[Link]
How components fit together overview
What is a layout manager?
▪ Each ViewGroup has a layout manager
▪ Use to position View items inside a RecyclerView
▪ Reuses View items that are no longer visible to the user
▪ Built-in layout managers
▪ LinearLayoutManager
▪ GridLayoutManager
▪ StaggeredGridLayoutManager
▪ Extend [Link]
What is an adapter?
▪ Helps incompatible interfaces work together
▪ Example: Takes data from database Cursor and prepares strings
to put into a View
▪ Intermediary between data and View
▪ Manages creating, updating, adding, deleting View items as
underlying data changes
▪ [Link]
What is a ViewHolder?
▪ Used by the adapter to prepare one View with data for one list
item
▪ Layout specified in an XML resource file
▪ Can have clickable elements
▪ Is placed by the layout manager
▪ [Link]
Implementing RecyclerView
1. Add RecyclerView dependency to [Link] if needed
2. Add RecyclerView to layout
3. Create XML layout for item
4. Extend [Link]
5. Extend [Link]
6. In Activity onCreate(), create RecyclerView with adapter and
layout manager
Summary
▪ After finishing this lecture, you should be able:
▪ to understand what a TextView and ScrollView are.
▪ to understand what Button and other input control views are.
▪ to understand Touch Gestures are.
▪ to briefly understand App bar, Dialog, and RecyclerView are.
NEXT WEEK’S OUTLINE
● Intent
● Activity Lifecycle
● Fragment
● Fragment Lifecycle
● Passing Data
REFERENCES
▪ [Link]. Beginning Android Programming with Android Studio (2017). John Wiley
& Son.
▪ D. Griffiths & D. Griffiths. Head First Android Development. O’Reilly
▪ Google Developer Training Team. Android Developer Fundamental Course: Learn to
develop Android Applications. Concept Reference. (Version 2: 2018). Google Inc.
▪ [Link]
concepts-v2/
Visi
Menjadi Program Studi Strata Satu Informatika unggulan yang menghasilkan lulusan
INFORMATIKA
berwawasan internasional yang kompeten di bidang Ilmu Komputer (Computer
Science), berjiwa wirausaha dan berbudi pekerti luhur.
Misi
1. Menyelenggarakan pembelajaran dengan teknologi dan kurikulum terbaik serta didukung
tenaga pengajar profesional.
2. Melaksanakan kegiatan penelitian di bidang Informatika untuk memajukan ilmu dan
teknologi Informatika.
3. Melaksanakan kegiatan pengabdian kepada masyarakat berbasis ilmu dan teknologi
Informatika dalam rangka mengamalkan ilmu dan teknologi Informatika.