View groups containers
Upcoming SlideShare
Loading in...5
×
 

View groups containers

on

  • 2,666 views

 

Statistics

Views

Total Views
2,666
Slideshare-icon Views on SlideShare
2,658
Embed Views
8

Actions

Likes
0
Downloads
70
Comments
0

2 Embeds 8

http://www.linkedin.com 7
https://www.linkedin.com 1

Accessibility

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.

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

    View groups containers View groups containers Presentation Transcript

    • 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.
    • 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
    • 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.
    • View
        •   CheckBox, TimePicker, DatePicker , GridView, ListView, 
        •   RadioButton, DigitalClock, EditText, TextView
        •   Gallery, ImageView, ProgressBar, VideoView
      • ViewGroup
        • LinearLayout
        • FrameLayout
        • TableLayout
        • RelativeLayout
        • AbsoluteLayout - Deprecated
        • ScrollView
    • 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.
    • 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;http://schemas.android.com/apk/res/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>
    • 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.
    • 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(R.id.text);
          • mButton = (Button) findViewById(R.id.text);
          • 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 R.java from resources by aapt tool during compilation.
    • 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);
      •     }
    • 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.
    • 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).
    • Layout attributes
      • LinearLayout, FrameLayout
        • ( layout_width  and  layout_height ), and each view is required to define them
        • layout_weight
        • layout_marginLeft
        • layout_gravity
      • http://developer.android.com/reference/android/widget/LinearLayout.LayoutParams.html
      • RelativeLayout
      • http://developer.android.com/reference/android/widget/RelativeLayout.LayoutParams.html
        • layout_weight, layout_gravity not defined for RelativeLayout params.
        • layout_toLeftOf
        • layout_above
        • layout_below
        • layout_aligParentLeft
    • 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 
    • 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.
    • layout_weight
      •  
    • 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.
    • 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;]
      • 
    • 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
    • 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
    • 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
    • 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”
    • 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
    • Important attributes
      • layout_weight
      • gravity, layout_gravity
      • padding, layout_margin
      • layout_centerHorizontal=&quot;true&quot; --> RelativeLayout
    • 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.
      • http://android-developers.blogspot.com/2009/02/android-layout-tricks-1.html
    • Layouts / Containers Heirarchy viewer: android-sdk/tools# ./hierarchyviewer
    • 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
    • Reference links
      • http://developer.android.com/guide/topics/ui/index.html
      • http://developer.android.com/guide/topics/ui/declaring-layout.html
      • http://developer.android.com/guide/developing/tools/layoutopt.html
      • http://blog.stylingandroid.com/archives/297
      • http://www.alittlemadness.com/2010/06/07/understanding-the-android-build-process/
      • http://android-developers.blogspot.com/2009/02/android-layout-tricks-1.html
    • 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.
    • 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.
    • 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.
    • AppWidget Framework
        • App Widget Provider Metadata XML file
        • AppWidgetProvider class
        • View layout
        • App Widget configuration Activity (Optional)
    • 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
    • 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
    • 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>
    • 2. Create App Widget Provider Info Metadata XML file
      • <appwidget-provider
      • xmlns:android=&quot;http://schemas.android.com/apk/res/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; com.example.android.ExampleAppWidgetConfigure&quot; >
      • </appwidget-provider>
      • previewImage --> Added in android 3.0
      • android:previewImage = &quot;@drawable/preview&quot; >
    • 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
    • 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)
    • Example programs
    • 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
    • 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().
    • 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.
    • 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). 
    • Overview of AppWidget mechanism
    • 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
    • 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.
    • 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.
    • 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
    • Demo snapshot 2x2 - 147dp width, 144dp height 4x2 - 294dp width, 144dp height
    • 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.
    • Reference links
      • http://developer.android.com/guide/topics/appwidgets/index.html
      • http://developer.android.com/guide/practices/ui_guidelines/widget_design.html
      • http://mylifewithandroid.blogspot.com/2010/01/remoteviews-as-hypertext-document.html
      • http://www.vogella.de/blog/2011/06/21/creating-bitmaps-from-the-internet-via-apache-httpclient/
      • http://code.google.com/apis/maps/documentation/staticmaps/
    • Thank you Mani.S Email: smanikandan14@gmail.com http://iserveandroid.blogspot.com/