Presentation is loading. Please wait.

Presentation is loading. Please wait.

Building User Interfaces and Basic Applications Chapter 2 1.

Similar presentations


Presentation on theme: "Building User Interfaces and Basic Applications Chapter 2 1."— Presentation transcript:

1 Building User Interfaces and Basic Applications Chapter 2 1

2 Objectives Become familiar with Android user interface Learn various views and widgets including view groups Implement applications that require various user interface controls Understand adaptive design concepts Use adapters to create sophisticated user interfaces 2

3 GUI Frameworks In General Model-View-Control (MVC) metaphor Event-based, implicit invocation style Single thread-ness Framework classes GUI components (views or widgets) Layout managers Events and event listeners Graphics and imaging classes Q: Example classes in Java AWT/Swing? *No AWT/Swing included in Android SDK 3

4 Model-View-Controller Android applications tend to rely on the Model- View-Controller design architecture. This architecture assigns one of three roles that objects can play in an application. 4 Model (data) View (UI element) Control update UI notify change notify user action update data

5 UI of Android App Defined in XML (e.g., res/layout/activity_main.xml) XML vocabulary compiled into corresponding GUI component classes Loaded at runtime in onCreate() method, e.g., setContentView(R.layout.activitiy_main) Q: Advantages in declaring UI in XML? Better separation of concerns (view from control) Visualization of UI structure Adaptive design (diversity, e.g., screen orientation) 5

6 GUI Components Views, widgets, and view groups Composite design pattern To allow clients to treat both single components and collections of component identically To define recursive data structures such as trees 6 ViewGroup View Client ImageView * >

7 View vs. ViewGroup UI components in android.view and android.widget View Has appearance on screen by occupying a rectangular area Is responsible for drawing and event handling Is a subclass of a base class android.view.View Examples: Button, TextView, EditText, ImageView, etc. ViewGroup A group of one or more views Provides the layout in which one can order the appearance and sequence of contained views Derived from the base class android.view.ViewGroup Can be combined Examples: AbsoluteLayout, RelativeLayout, LinearLayout, TableLayout,, FrameLayout, ListView, GridView, ScrollView, WebView, etc. 7

8 Layout Responsible for arranging its child views (positions and sizes), directly affecting the look and feel of an application Several possibilities Manually specify absolute positions Manually specify relative positions Automate it Q: Pros and cons? 8

9 Layout: AWT/Swing vs. Android AWT/Swing Strategy design pattern Layout manager for container Android Separate view group for each layout, E.g., LinearLayout (~ FlowLayout) TableLayout (~ GridLayout) RelativeLayout (~ GridBagLayout?) Q: Pros and cons? 9 GridLayout LayoutManager Container FlowLayout

10 Attributes of Views Required attributes layout_width layout_height => layout knows how to size a view 10 android:layout_height="wrap_content" android:layout_width="match_parent" (previously "fill_parent“) *can be specified in a measurement unit

11 Attributes of Views Other common attributes Id (e.g., android:id=“@+id/startButton”) layout_marginTop layout_marginBottom layout_marginLeft layout_marginRight layout_gravity (alignment: i.e., left, center, right) layout_weight... 11

12 Unit of Measurements Concern: devices with different densities (dpi, dot per inch) Screen densities for Android Low density (ldpi): 120 dpi Medium density (mdpi): 160 dpi High density (hdpi): 240 dpi Extra high density (xhdpi): 320 dpi Extra extra high density (xxhdpi): 480 dpi Extra extra extra high density (xxxhdpi): 640 dpi 12

13 Different Units dp: density-independent pixel 160dp = 1" of physical screen size dp to screen pixels (px): px = dp x (dpi / 160) Same ratio on different devices; recommended sp: scale-independent pixel Similar to dp for specifying font size; recommended pt: point 1 pt = 1/72" of physical screen size; not recommended px: pixel Actual pixel of screen; not recommended 13

14 More on Layouts Commonly used layouts RelativeLayout LinearLayout TableLayout GridLayout FrameLayout 14

15 15

16 LinearLayout Arranges its children either horizontally or vertically, depending on the value of its orientation property, (android:orientation="horizontal" or "vertical") Easiest layout to use Attributes for children layout_gravity="right“ layout_weight="0.8" gravity: specify how child views are positioned, weight: specify how extra spaces are allocated, 80% of extra space to the child (if total is 1). 16

17 RelativeLayout Most powerful layout available. Children positioned relative to each other or to their parent. Types of relationships: To the left, right, above or below the specified element (layout_toLeftOf, layout_toRightOf, layout_above, layout_below) Aligned by the left, right, top or bottom edge of the specified element (layout_alignLeft, layout_alignRight, layout_alignTop, layout_alignBottom) Aligned by the left, right, top or bottom edge of a parent (layout_alignParentLeft, layout_alignParentRight, layout_alignParentTop, layout_alignParentBottom) Centered vertically, centered horizontally, centered vertically and horizontally relative to its parent (layout_centerVertical, layout_centerHorizontal, layout_centerInParent) 17

18 18 android:layout_alignParentTop=“true” android:layout_alignParentLeft=“true” android:layout_alignParentStart=“true” android:layout_below=“@id/text1” android:layout_alignLeft=“@id/text1” android:layout_alignStart=“@id/text1” android:layout_toRightOf=“@id/text2” android:layout_alignBottom=“@id/text2” android:layout_below=“@id/button” android:layout_alignLeft=“@id/button” android:layout_alignStart=“@id/button”

19 TableLayout Arrange child views in rows and columns Often used for organizing data content into tabular form Subclass of LinearLayout. Use a TableRow element to add a row. 19

20 GridLayout Places its children in a rectangular grid Can place children quickly without requiring a table Can place children in a controlled way by specifying a row-and-column location or using layout_row and layout_column attribute Horizontal vs vertical orientation 20 <GridLayout... android:columnCount=“2” android:rowCount=“2” android:orientation=“horizontal”>

21 FrameLayout Placeholder on screen that can be used to display a single view. Multiple views stacked in a frame layout, i.e., position children on top of each other. 21

22 Text Input and Output TextView: primarily for text output EditText: text input and editing by the user using (soft) keyboard TextView EditText View

23 Many Public Methods Refer to API docs TextView void setText(CharSequence) CharSequence getText() Int length() // number of chars void addTextChangedListener(TextWatcher) … EditText Editable getText() // Editable ---|> CharSequence void setSelection(int, int) … Q: Similar AWT/Swing widgets? 23

24 EditText Input Types Text FieldinputType Property Value Plain textnone Person nametextPersonName PasswordtextPassword Password (Numeric)numberPassword E-mailtextEmailAddress Phonephone Postal addresstextPostalAddress 24 <EditText... androd:hint=“email address” android:inputType=“textEmailAddress” />

25 Lab 2-1: Shipping Calculator Pages: 106-118 Application settings Application name: Shipping Calculator Company name: cs4330.cs.utep.edu Android features RelativeLayout TextView EditText TextWatcher on EditText Image files from course website 25

26 Views and Widgets Many different views and widgets Basic views: simple, commonly used views, e.g., TextView, EditText, and Button Picker views: views for selecting from a list, e.g., TimePicker and DatePicker List views: views for displaying a long list of items, e.g., Spinner and ListView Container views: views containing other views, e.g., RadioGroup, GridView, ScrollView, and VideoView. 26

27 27

28 Basic Views TextView: displaying text (a.k.a. label) Button: push-button widget ImageButton: button that can also display an image EditText: editing text (subclass of TextView) AutoCompleteTextView: show a list of completion suggestions CheckBox: two-state button: checked or unchecked RadioButton: two states: checked or unchecked RadioGroup: grouping of radio buttons ToggleButton: displaying checked/unchecked states using a light indicator with text "On" and "Off“ … 28

29 Class Hierarchy View (android.view) TextView (android.widget) Button CompoundButton (abstract) CheckBox RadioButton ToggleButton EditText ViewGroup (android.view) LinearLayout (android.widget) RadioGroup 29

30 Handling Events Register a handler after getting a reference to view (use findViewById) Use XML onClick attribute for OnClickListener 30 View: setOnClickListener(View.OnClickListener) *work for all views including various buttons RadioGroup: setOnCheckedChangeListener(OnCheckedChangeListener) <Button... android:onClick=“buttonClicked"/>

31 ProgressBar Visual indicator of progress in a given operation Default mode Indefinite/indeterminate meaning that it shows a cyclic animation Useful for tasks having no clear indication when they will be completed, e.g., sending data to web service Termination: setVisibility(int) -- not synchronized 0: View.VISIBLE; 4: View.INVISIBLE; 8: View.GONE Communication with progress bar: runOnUiThread(Runnable), Handler.post(Runnable), ASyncTask Customization Use style attribute: style="?android:attr/progressBarStyleHorizontal" Control: ProgressBar.setMax(int) -- synchronized ProgressBar.setProgress(int) -- synchronized ProgressBar.dismiss() -- synchronized 31

32 ViewGroup Container of view objects Special view to hold groups of views Invisible that organizes child views 32

33 RadioGroup and RadioButton A radio button is specifically used when a single item from a collection of items must be made. If a radio button is already selected, it will be de- selected when another radio button in the collection is selected. Do Lab 2-2 Burger Calorie Calculator (p. 127) 33

34 Adaptive Design Concepts - Screens and Orientations Challenge Diversity of devices such as screen size and density, e.g., many variations in screen sizes that are available on the market at any given time. Adaptive design Adaptation of a layout design to fit an individual screen size and or orientation. Important to Android because it supports flexibility when designing an app that can work on multiple devices.

35 Adapting to Different Screen Sizes Use screen size qualifiers, e.g., layout-xlarge Screen sizes small: 426dp x 320dp normal: 470dp x 320dp large: 640dp x 480dp xlarge: 960dp x 720dp New qualifier (since Android 3.2) sw dp (smallest width), w dp, h dp, e.g., sw320dp typical phone sw480dp tweener tablet sw600dp 7" tablet sw720dp 10" tablet 35

36 Adapting to Screen Orientation Techniques for handling screen orientation changes Fix or force screen orientation (portrait or landscape) Adapt to orientation changes (i.e., resize and reposition) Forcing screen orientation In AndroidManifest.xml android:screenOrientation=“landscape” for each activity In activity class setRequestOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT) 36

37 Adapting to Orientation Changes Two techniques Anchoring: anchor views to four edges of the screen (use RelativeLayout) Resizing and repositioning Resizing and repositioning views according to the current screen orientation Use layout qualifier and multiple XML files, e.g., res/layout/activity_main.xml (for all modes) res/layout-port/activity_main.xml (for portrait mode) res/layout-land/activity_main.xml (for landscape mode) 37

38 Detecting Orientation Changes Use WindowManager to get the current display and compare display width and height, e.g., 38 WindowManager wm = getWindowManager(); Display d = wm.getDefaultDisplay(); if (d.getWidth() > d.getHeight())... landscape else... portrait

39 Lab 2-3: Shipping Calculator II Pages 144-153; portrait and landscape 39

40 Container Views Containers (view group) for other views, e.g., ListView: items displayed in a vertically scrolling list GridView: items displayed in a two-dimensional scrolling grid. ExpandableListView: extension of a ListView to support two levels … 40

41 Providing Data to Container Views Challenge Many different data sources, e.g., arrays, collections, and database Many different ways of displaying them, e.g., Spinner, ListView, and GridView Q: How to bind them together? Q: Any design pattern for this? 41 Array List Database …

42 Adapter Bind a data source to an container view (AdapterView) Provides a common interface to the data model behind an AdapterView such as ListView Responsible for accessing the data to be supplied to a container widget and converting the individual elements of data into a specific view Behaves as a middleman between the data source and the adapterView. 42 ArrayAdapter AdapterView > Adapter ListView array

43 ListView Display a list of items in a vertically scrolling list Providing a list of data to display setAdaper(ListAdapter) ListAdapter: subinterface of Adapter with many subclasses including: ArrayAdapter BaseAdapter (abstract) CursorAdapter (abstract) SimpleBaseAdapter SimpleCursorAdapter … Listener: OnItemSelectedListener 43

44 ListView (Cont.) Customization setChoiceMode(int): none (ListView.CHOICE_MODE_NONE), single, multiple setTextFilterEnabled(boolean): let the view filter to match what is typed on the keypad setItemChecked(int, boolean) Storing and retrieving items from strings.xml getResources().getStringArray(R.array.my_array) 44

45 Example: List of Deserts Section 9.6 Adapter and AdapterView (p. 765-769) ListView and ArrayAdapter 45 Variation: Store names in strings.xml and use getResources().getStringArray (int) to retrieve them

46 Do Lab 2-2, 2-4, or 2-5 Lab 2-2 Burger Calorie Calculator (p. 127) - RadioButton, CheckBox, SeekBar Lab 2-4 Simple Calculator (p. 155) - TableLayout Lab 2-5 Renaissance Paintings (p. 173) - ScrollView 46


Download ppt "Building User Interfaces and Basic Applications Chapter 2 1."

Similar presentations


Ads by Google