View groups containers
-
Upload
mani-selvaraj -
Category
Technology
-
view
2.456 -
download
4
Transcript of View groups containers
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 layoutsThe 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="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" > <TextView android:id="@+id/text" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Hello, I am a TextView" /> <Button android:id="@+id/button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Hello, I am a Button" /></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("Accesing elements from XML..");
mButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mTextView.setText("Text changed on Button Click");
}
});
}
- 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("Instantiating layout elements runtime"); 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("Click here..."); // 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("Text changed on Button Click");
}
}); 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="30dp"
• Some are common to all View objects, because they are inherited from the root View class (like the id attribute).
android:id="@+id/my_button"
Layout attributes
• Some attributes are considered "layout parameters," 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 attributesLinearLayout, 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
RelativeLayouthttp://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 margins between children and
the gravity (right, center, or left alignment) of each child
• " layout_weight "- This attribute assigns an "importance" 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
Row 1 Row 2 Row 3 Row 40
2
4
6
8
10
12
Column 1
Column 2
Column 3
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 widthto 0 (zero); then assign relative weight values to each child, depending on what proportion of the screen each should have.
layout_gravity, gravityThe 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:paddingRightandroid:paddingTop,android:paddingBottom
android:marginandroid:marginLeft,android:marginRightandroid: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
<Buttonandroid:layout_width="125px"android:layout_height="wrap_content"android:text="Send"android:layout_below="@+id/txtComments"android:layout_alignLeft="@+id/txtComments"/><Buttonandroid:layout_width="125px"android:layout_height="wrap_content"android:text="Cancel"android:layout_below="@+id/txtComments"android:layout_alignRight="@+id/txtComments"/>
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 attributeslayout_weightgravity, layout_gravitypadding, layout_marginlayout_centerHorizontal="true" --> 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
o Describes the metadata for an App Widget, such as minimum width, minimum height, update frequency, the AppWidgetProvider class.
o It also references App widget's layout fileo This should be defined in res/xml folder.
• AppWidgetProvider classo 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.)
o 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="ExampleAppWidgetProvider" ><intent-filter><action android:name="android.appwidget.action.APPWIDGET_UPDATE" /></intent-filter><meta-data android:name="android.appwidget.provider"android:resource="@xml/example_appwidget_info" /></receiver>
2. Create App Widget Provider Info Metadata XML file<appwidget-providerxmlns:android="http://schemas.android.com/apk/res/android"android:minWidth="294dp"android:minHeight="72dp"android:updatePeriodMillis="86400000" --> Every one dayandroid:initialLayout="@layout/example_appwidget"android:configure="com.example.android.ExampleAppWidgetConfigure" ></appwidget-provider>
previewImage --> Added in android 3.0
android:previewImage="@drawable/preview">
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 classeso FrameLayout, LinearLayout, RelativeLayoyto AnalogClock, Button, Chronometer, ImageButton,o ImageView, ProgressBar, TextView
• Android 3.0 supports additional widgetso ListViewo GridViewo StackViewo 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[]) - calledwhen 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 widgetsDeclare AppWidgetProviderInfo metafiles 4x1,4x2,2x22x2 :android:minWidth="147dp"android:minHeight="142dp"4x2 :android:minWidth="294dp"android:minHeight="142dp"
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.
o 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 overviewOnUpdate / onDeleted Pass AppWidgetIdstartService(intent)
updateWidget(AppWidgetId, remoteview)
1
Service
LocationIdentifier – GPS/Wifi
Fetch the map4
9updateWidget(AppWidgetId, remoteview)
updateWidget(AppWidgetId, remoteview)
OnUpdate / onDeleted Pass AppWidgetIdstartService(intent)
OnUpdate / onDeleted Pass AppWidgetIdstartService(intent)
Gogle static map
2
Latitude,longitude
Spwan a thread
AppWidget
AppWidget
AppWidget
Maintains list of AppWidgetIds, AppwidgetType
3
5
6
6
Demo snapshot2x2 - 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 : 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 linkshttp://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.SEmail: [email protected]://iserveandroid.blogspot.com/