View groups containers
Upcoming SlideShare
Loading in...5

Like this? Share it with your network


View groups containers






Total Views
Views on SlideShare
Embed Views



2 Embeds 15 8 7


Upload Details

Uploaded via as Microsoft PowerPoint

Usage Rights

© All Rights Reserved

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
Post Comment
Edit your comment

View groups containers Presentation Transcript

  • 1. Topics
    • ViewGroups
      • What is viewgroup/layouts/containers?
      • XML & Custom based layouts.
      • Different types of layouts, LinearLayouts,FrameLayout,RelativeLayout, TableLayout.
      • Attributes of layout
      • Code snippets demonstrating each of layouts.
      • Tools to analyse the layouts (Hierarchy viewer,layoutopt )
    • HomeScreen Widgets
      • What is an AppWidget ?
      • AppWidget framework
      • Steps for creating an AppWidget
      • Example demonstrating widget showing google static map of location as home screen widget.
  • 2. View
      • In an Android application, the user interface is built using  View  and  ViewGroup  objects. There are many types of views and view groups, each of which is a descendant of the  View  class.
      • View objects are the basic units of user interface expression on the Android platform. 
      • The View class serves as the base for subclasses called "widgets," which offer fully implemented UI objects, like text fields and buttons
  • 3. ViewGroups / Containers / Layouts
      •   The ViewGroup class serves as the base for subclasses called "layouts," which offer different kinds of layout architecture, like linear, table and relative.
      • An Android layout is a class that handles arranging the way its children appear on the screen.  Anything that is a View (or inherits from View) can be a child of a layout. All of the layouts inherit from ViewGroup (which inherits from View) so you can add views to it.
      • Containers/LayoutManagers are another terminologies to layouts.
  • 4. View
      •   CheckBox, TimePicker, DatePicker , GridView, ListView, 
      •   RadioButton, DigitalClock, EditText, TextView
      •   Gallery, ImageView, ProgressBar, VideoView
    • ViewGroup
      • LinearLayout
      • FrameLayout
      • TableLayout
      • RelativeLayout
      • AbsoluteLayout - Deprecated
      • ScrollView
  • 5. Two ways of defining layouts
    • The Android framework gives you the flexibility to use two methods for declaring and managing your application's UI.
      • Declare UI elements in XML . Android provides a straightforward XML vocabulary that corresponds to the View classes and subclasses, such as those for widgets and layouts.
      • Instantiate layout elements at runtime . Your application can create View and ViewGroup objects (and manipulate their properties) programmatically.
  • 6. XML definitions of layouts
      • The most common way to define your layout and express the view hierarchy is with an XML layout file. XML offers a human-readable structure for the layout, much like HTML. Each element in XML is either a View or ViewGroup object (or a descendant )
      • <? xml version = &quot;1.0&quot; encoding = &quot;utf-8&quot; ?> <LinearLayout xmlns:android = &quot;;               android:layout_width = &quot;fill_parent&quot;               android:layout_height = &quot;fill_parent&quot;               android:orientation = &quot;vertical&quot; >     <TextView android:id = &quot;@+id/text&quot;               android:layout_width = &quot;wrap_content&quot;               android:layout_height = &quot;wrap_content&quot;               android:text = &quot;Hello, I am a TextView&quot; />     <Button android:id = &quot;@+id/button&quot;             android:layout_width = &quot;wrap_content&quot;             android:layout_height = &quot;wrap_content&quot;             android:text = &quot;Hello, I am a Button&quot; /> </LinearLayout>
  • 7. XML definitions of layouts
      • You could declare your application's layouts in XML, including the screen elements that will appear in them and their properties..
      • The advantage to declaring your UI in XML is that it enables you to better separate the presentation of your application from the code that controls its behavior.
  • 8. Accessing UI elements from XML
      • You could then add code in your application that would modify the state of the screen objects, including those declared in XML, at run time.
      • public void onCreate(Bundle savedInstanceState) {
        • super.onCreate(savedInstanceState);
        • setContentView(R.layout.main);
        • mTextView = (TextView) findViewById(;
        • mButton = (Button) findViewById(;
        • mTextView.setText(&quot;Accesing elements from XML..&quot;);
        • mButton.setOnClickListener(new View.OnClickListener() {
          • @Override
          • public void onClick(View v) {
            • mTextView.setText(&quot;Text changed on Button Click&quot;);
          • }
        • });
      • }
      • - Generation of from resources by aapt tool during compilation.
  • 9. Instantiate layout elements at runtime .
    •     public void onCreate(Bundle savedInstanceState) {
    •         super.onCreate(savedInstanceState);
    •         //setContentView(R.layout.main);
    •         LinearLayout mainLayout = new LinearLayout(this);
    •         mainLayout.setOrientation(LinearLayout.VERTICAL);
    •         //Create the child element
    •         mTextView = new TextView(this);
    •         mTextView.setText(&quot;Instantiating layout elements runtime&quot;);
    •         mTextView.setTextSize(30);
    •         //Add to main layout.
    •         LinearLayout.LayoutParams params = new LinearLayout.LayoutParams((LayoutParams.WRAP_CONTENT,
      • LayoutParams.WRAP_CONTENT);
    •         mainLayout.addView(mTextView, params);
    •         //Create child element
    •         mButton = new Button(this);
    •         mButton.setText(&quot;Click here...&quot;);
    •         // Add to main layout
    •         params = new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.WRAP_CONTENT);
    •         mainLayout.addView(mButton, params);
    •         mButton.setOnClickListener(new View.OnClickListener() {
      • @Override
      • public void onClick(View v) {
        • mTextView.setText(&quot;Text changed on Button Click&quot;);
      • }
      • });
    •         setContentView(mainLayout);
    •     }
  • 10. Attributes
      • Every View and ViewGroup object supports their own variety of XML attributes. Some attributes are specific to a View object (for example, TextView supports the  textSize  attribute), 
      • android:textSize=&quot;30dp&quot;
      •   Some are common to all View objects, because they are inherited from the root View class (like the  id  attribute). 
      • android : id = &quot;@+id/my_button&quot;
    • Layout attributes
      • Some attributes are considered &quot;layout parameters,&quot; which are attributes that describe certain layout orientations of the View object, as defined by that object's parent ViewGroup object.
  • 11. Layout attributes
      • XML layout attributes named  layout_ something  define layout parameters for the View that are appropriate for the ViewGroup in which it resides.
      • Every ViewGroup class implements a nested class that extends  ViewGroup.LayoutParams . This subclass contains property types that define the size and position for each child view, as appropriate for the view group. As you can see in figure, the parent view group defines layout parameters for each child view (including the child view group).
  • 12. Layout attributes
    • LinearLayout, FrameLayout
      • ( layout_width  and  layout_height ), and each view is required to define them
      • layout_weight
      • layout_marginLeft
      • layout_gravity
    • RelativeLayout
      • layout_weight, layout_gravity not defined for RelativeLayout params.
      • layout_toLeftOf
      • layout_above
      • layout_below
      • layout_aligParentLeft
  • 13. LinearLayout
      • LinearLayout organizes elements along a single line. You specify whether that line is verticle or horizontal using android:orientation
      • vertical list will only have one child per row, no matter how wide they are.
      • a horizontal list will only be one row high 
  • 14. LinearLayout - Attributes
      •   A linearlayout respects  margin s between children and the  gravity  (right, center, or left alignment) of each child
      •   &quot; layout_weight &quot; - This attribute assigns an &quot;importance&quot; value to a view, and allows it to expand to fill any remaining space in the parent view. Child views can specify an integer weight value, and then any remaining space in the view group is assigned to children in the proportion of their declared weight. Default weight is zero. 
      • If we are dividing the parent in to equal parts, we just set the children’s layout_weights all to 1. But if we want to divide it unequally, we can do that in a number of ways. We can either use decimal fractional values which total 1, or we can use integer values.
  • 15. layout_weight
  • 16. layout_weight -- Proportinate fill
      • To create a proportionate size layout on the screen, create a container viewgroup object with the  layout_width  and  layout_height   attributes set to  fill_parent ; assign the children  height  or width to  0  (zero); then assign relative  weight  values to each child, depending on what proportion of the screen each should have.
  • 17. layout_gravity, gravity
    • The difference between android:gravity and android:layout_gravity is that
    • * android:gravity  positions the contents of that view (i.e. what’s inside the view), [code : setGravity() ] whereas  
      • * android:layout_gravity  positions the view with respect to its parent (i.e. what the view is contained in).  [  params .gravity = Gravity .BOTTOM;]
  • 18. layout_margins, padding
      • Padding is giving space within the view.
      • Margin is giving spaces outside the view where the view is placed in.(between the two elements)
    • android:padding 
    • android:paddingLeft,android:paddingRight
    • android:paddingTop,android:paddingBottom
    • android:margin
    • android:marginLeft,android:marginRight
    • android:marginTop,android:marginBottom
  • 19. RelativeLayout
      • RelativeLayout lays out elements based on their relationships with one another, and with the parent container.
    • Relative To Container(parent):
    • These properties will layout elements relative to the parent container.
      • android:layout_alignParentBottom – Places the bottom of the element on the bottom of the container
      • android:layout_alignParentLeft – Places the left of the element on the left side of the container
      • android:layout_alignParentRight – Places the right of the element on the right side of the container
      • android:layout_alignParentTop – Places the element at the top of the container
      • android:layout_centerHorizontal – Centers the element horizontally within its parent container
      • android:layout_centerInParent – Centers the element both horizontally and vertically within its container
      • android:layout_centerVertical – Centers the element vertically within its parent container
  • 20. RelativeLayout
    • Relative To Other Elements
      • These properties allow you to layout elements relative to other elements on screen. One thing to remember is that referencing an element before it has been declared will produce an error.
      • android:layout_above – Places the element above the specified element
      • android:layout_below – Places the element below the specified element
      • android:layout_toLeftOf – Places the element to the left of the specified element
      • android:layout_toRightOf – Places the element to the right of the specified element
    • Alignment With Other Elements
      • These properties allow you to specify how elements are aligned in relation to other elements. 
      • android:layout_alignBaseline – Aligns baseline of the new element with the baseline of the specified element
      • android:layout_alignBottom – Aligns the bottom of new element in with the bottom of the specified element
      • android:layout_alignLeft – Aligns left edge of the new element with the left edge of the specified element
      • android:layout_alignRight – Aligns right edge of the new element with the right edge of the specified element
      • android:layout_alignTop – Places top of the new element in alignment with the top of the specified element
  • 21. RelativeLayout
    • <Button
    • android:layout_width=&quot;125px&quot;
    • android:layout_height=&quot;wrap_content&quot;
    • android:text=&quot;Send&quot;
    • android:layout_below=&quot;@+id/txtComments&quot;
    • android:layout_alignLeft=&quot;@+id/txtComments&quot;
    • />
    • <Button
    • android:layout_width=&quot;125px&quot;
    • android:layout_height=&quot;wrap_content&quot;
    • android:text=&quot;Cancel&quot;
    • android:layout_below=&quot;@+id/txtComments&quot;
    • android:layout_alignRight=&quot;@+id/txtComments&quot; />
    • alignifParentMissing=”true”
  • 22. FrameLayout
      •   Adds view on top of another in the order the views are defined in XML.
      • framelayout positions all child elements   on the top left of the screen. (if gravity is not specified)
    • - ImageView
    • - TextView
    • - Button
  • 23. Important attributes
    • layout_weight
    • gravity, layout_gravity
    • padding, layout_margin
    • layout_centerHorizontal=&quot;true&quot; --> RelativeLayout
  • 24. LinearLayout Vs RelativeLayout
      •   All difficult layouts can be visualised in relativelayout.
      •   To avoid more nested layouts it is recommended to use relativelayout.
      •   Dont use absolutelayout as it is difficult to handle different resolutions. Involved tedious work.
    • One scenario is when views are returned to listview it should be as simple as possible. so relativelayouts help to avoid more nested layouts.
  • 25. Layouts / Containers Heirarchy viewer: android-sdk/tools# ./hierarchyviewer
  • 26. layoutopt tool
      • layoutopt  is a command-line tool that helps you optimize the layouts and layout hierarchies of your applications.
    • samples / too_many . xml     7 : 413 The root - level < FrameLayout /> can be replaced with < merge />     - 1 :- 1 This layout has too many views : 81 views , it should have <= 80 ! samples / useless . xml     7 : 19 The root - level < FrameLayout /> can be replaced with < merge />     11 : 17 This LinearLayout layout or its FrameLayout parent is useless
  • 27. Reference links
  • 28. Home screen widgets
      • What is an AppWidget ?
      • AppWidget framework
      • Steps for creating an AppWidget
      • Example demonstrating widget showing google static map of location as home screen widget.
  • 29. What is an App Widget??
    • App Widgets are miniature application views that can be embedded in other applications (such as the Home screen) and receive periodic updates.
  • 30. Appwidget usages
      • People can drop widgets onto their home screen and interact with them
      • Widgets can provide a quick glimpse into full-featured apps, such as showing upcoming calendar events, or viewing details about a song playing in the background.
      • Users can also interact with your app through the widget, for example pausing or switching music tracks.
  • 31. AppWidget Framework
      • App Widget Provider Metadata XML file
      • AppWidgetProvider class
      • View layout
      • App Widget configuration Activity (Optional)
  • 32. AppWidget Framework
      •   App Widget Provider Metadata XML file
        • Describes the metadata for an App Widget, such as minimum width, minimum height, update frequency, the AppWidgetProvider class.
        • It also references App widget's layout file
        • This should be defined in res/xml folder.
      •   AppWidgetProvider class
        • Defines the basic methods that allow you to programmatically interface with the App Widget, based on broadcast events. (AppWidgetProvider class is a child class of BroadcastReceiver class.)
        • Through it, you will receive broadcasts when the ApWidget is updated, enabled, disabled and deleted
  • 33. Steps for Building an App Widget
      • Declare an AppWidgetProvider in the Manifestfile
      • Create the App Widget Provider Info Metadata XML file
      • Create the App Widget Layout XML file
      • Write the AppWidgetProvider Class
  • 34. 1. Declare AppWidgetProvider in Manifest
    • <receiver android:name=&quot;ExampleAppWidgetProvider&quot; >
    • <intent-filter>
    • <action android:name=&quot; android.appwidget.action.APPWIDGET_UPDATE &quot; />
    • </intent-filter>
    • < meta-data android:name=&quot;android.appwidget.provider&quot;
    • android:resource=&quot;@xml/ example_appwidget_info &quot; />
    • </receiver>
  • 35. 2. Create App Widget Provider Info Metadata XML file
    • <appwidget-provider
    • xmlns:android=&quot;;
    • android:minWidth=&quot;294dp&quot;
    • android:minHeight=&quot;72dp&quot;
    • android:updatePeriodMillis=&quot; 86400000 &quot;  --> Every one day
    • android:initialLayout=&quot;@layout/example_appwidget&quot;
    • android:configure=&quot;; >
    • </appwidget-provider>
    • previewImage --> Added in android 3.0
    • android:previewImage = &quot;@drawable/preview&quot; >
  • 36. 3. Create App Widget Layout
      • App Widget layouts are based on RemoteViews,which do not support every kind of layout or view widget.
      • A RemoteViews object (and, consequently, an App Widget) can support the following layouts and Widget classes
        • FrameLayout, LinearLayout, RelativeLayoyt
        • AnalogClock, Button, Chronometer, ImageButton,
        • ImageView, ProgressBar, TextView
      • Android 3.0 supports additional widgets
        • ListView
        • GridView
        • StackView
        • AdapterViewFlipper
  • 37. 4. Write AppWidgetProvider Class
      • The  AppWidgetProvider  class extends BroadcastReceiver to handle the App Widget broadcasts. The AppWidgetProvider receives only the event broadcasts that are relevant to this App Widget, such as when the App Widget is updated, deleted, enabled, and disabled. 
    • Methods to override
      • onUpdate(Context, AppWidgetManager, int[]) - called
    • when each App Widget is added to a host (unless you use a configuration Activity), Typically the onlymethod that needs to be present
      • onDeleted(Context, int[])
      • onEnabled(Context)
      • onDisabled(Context)
      • onReceive(Context, Intent)
  • 38. Example programs
  • 39. AppWidget provider - onUpdate
      • Only one  updatePeriodMillis  schedule will be managed for all instances of the App Widget.
      • Because  AppWidgetProvider  is an extension of  BroadcastReceiver , your process is not guaranteed to keep running after the callback methods return i.e onUpdate,onEnabled.
      • Consider starting a  Service  in the  onUpdate()  method. 
      • To update an appWidget all you need to know is AppWidgetId and have AppWidgetManager instance
  • 40. Use AlarmManager to update
      • The disadvantage with updateperiodMillis is that minimum value 30 mins . Cannot update the widget before that.
      • AlarmManager helps in updating the widget 
      • final AlarmManager m = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE); 
      • final Intent intent = new Intent(context, MyService.class);  
      • if (service == null)  
      • {  
      • service = PendingIntent.getService(context, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT);
      • }  
      • m.setRepeating(AlarmManager.RTC, System.currentTimeMillis(), 1000 * 60, service); 
      • In service - onStartCommand() - updateWidget().
  • 41. Service
      • A  Service  is an application component that can perform long-running operations in the background and does not provide a user interface.
    • onStartCommand()
      • The system calls this method when another component, such as an activity, requests that the service be started, by calling startService().
    • A service runs in the main thread of its hosting process - Spawn thread to do perform CPU intesive operations to avoid ANRs.
  • 42. Remoteviews
      • RemoteViews  is the key mechanism behind the AppWidget feature of the Android platform.
      •   RemoteViews is a parcelable data structure that can be sent through Android IPC (Inter Process Communication).
      • AppWidgets are broadcast event receivers, they process broadcasts from Launcher and respond with RemoteViews. When the RemoteViews data structure is received and deserialized, it can be applied to any ViewGroup of the UI and can therefore appear on the UI of another application (Launcher). 
  • 43. Overview of AppWidget mechanism
  • 44. Multiple sized widgets
    • Declare AppWidgetProviderInfo metafiles 4x1,4x2,2x2
    • 2x2 :
    • android:minWidth=&quot;147dp&quot;
    • android:minHeight=&quot;142dp&quot;
    • 4x2 :
    • android:minWidth=&quot;294dp&quot;
    • android:minHeight=&quot;142dp&quot;
    • Define corresponding Appwidget classes.
    • Declare corresponding AppWidget Broadcast receivers in AndroidManifest.xml
  • 45. Things to keep in mind 
      • Frequency of update should not be high. ex. every 5 mins.It will reduce the battery life of the phone.
        • Handled badly your widget could end up making the phone completely unresponsive. Pushing updates to onscreen widgets is a somewhat costly process.
      • Avoid nesting of layouts within a layout.
      • Give proper padding. As it might collide with adjacent widget. No boundary seperation would be seen.
      • Offload any webrequest through a service to avoid ANRs.
  • 46. Location based map 
    • onEnabled() -> Start a service
    • onUpdate() -> Get the appWidgetId and appWidgetType and pass to the service.
    • onDeleted() -> Get the appWidgetId and pass to the service.
    • Service -> Listens for movement change using PhoneStateListener and fetches current location using GPS or Wifi and downloads the static map as Bitmap  and updates the widgets 2x2 and 4x2.
  • 47. Implementation overview OnUpdate / onDeleted Pass AppWidgetId startService(intent) updateWidget(AppWidgetId, remoteview) Service LocationIdentifier – GPS/Wifi Fetch the map updateWidget(AppWidgetId, remoteview) updateWidget(AppWidgetId, remoteview) OnUpdate / onDeleted Pass AppWidgetId startService(intent) OnUpdate / onDeleted Pass AppWidgetId startService(intent) Gogle static map Latitude,longitude Spwan a thread AppWidget AppWidget AppWidget Maintains list of AppWidgetIds, AppwidgetType 3 5 6 6 1 4 9 2
  • 48. Demo snapshot 2x2 - 147dp width, 144dp height 4x2 - 294dp width, 144dp height
  • 49. To try out in demo
    • -   Add an Button on widgets to let user decide location movement detection ON/OFF and decide updating the widget based on that.
    •   CLUE : Add a pendingIntent for the button click to call the same service with an SETTING_ID and check for the intent value in onStartCommand to update the widget.
    • Add Configure activity and get the inputs from user. 
      • Basically collect some settings values like movement detection On/Off
      • Store it in sharedpereferences
      • Read the values from sharedpereferences in service and take appropriate action in code.
  • 50. Reference links
  • 51. Thank you Mani.S Email: