Assignment 2

Welcome to week two of Mobile Systems and Applications! (cs.upt.ro/~alext/msa/lab2)

Topics of discussion

  • More about views, placement layouts, activities.

  • Displaying dialogs, toasts and material design elements.

  • Explicit and implicit intents.

Activities

An activity is a single, focused thing that the user can do. Almost all activities interact with the user, so the Activity class takes care of creating a window for you in which you can place your UI with setContentView. While activities are often presented to the user as full-screen windows, they can also be used as floating windows (via a theme with windowIsFloating set) or embedded inside of another activity (using ActivityGroup). Every activity must implement the onCreate method - here is where you initialize your activity. Most importantly, you will usually call setContentView with a layout resource defining your UI, and use findViewById to retrieve the widgets in that UI that you need to interact with programmatically.

The user interface for an activity is provided by a hierarchy of views (derived from the View class). Each view controls a particular rectangular space within the activity's window and can respond to user interaction. For example, a view might be a button that initiates an action when the user touches it.

Android provides a number of ready-made views that you can use to design and organize your layout. Widgets are views that provide visual (and interactive) elements for the screen, such as a button, text field, checkbox, or just an image. Layouts are views derived from ViewGroup that provide a unique layout model for its child views, such as a linear layout, a grid layout, or relative layout. You can also subclass the View and ViewGroup classes (or existing subclasses) to create your own widgets and layouts and apply them to your activity layout.

The most common way to define a layout using views is with an XML layout file saved in your application resources. This way, you can maintain the design of your user interface separately from the source code that defines the activity's behavior. You can set the layout as the UI for your activity with setContentView, passing the resource ID for the layout. However, you can also create new Views in your activity code and build a view hierarchy by inserting new Views into a ViewGroup, then use that layout by passing the root ViewGroup to setContentView. Read more about activities online.

Layouts and other views

Layouts in Android are a type of ViewGroup, one of the many subclasses of View. They are meant to organize the UI structure of an activity so that users get the same experience across different devices (e.g. resolutions, screen orientations, screen formats). A ViewGroup is the only type of view that is compound, meaning that it may hold other viewgroups and views inside (the best analogy would be with folders and files). See an example in Figure 1.

Fig.1.

Android has defined the following hierarchy for the view class, as depicted in Figure 2. The most notable layouts are:

  • LinearLayout - aligns all children in a single direction, vertically or horizontally. Each element is given an equal amount of horizontal or vertical space. You can specify the layout direction with the orientation tag, and you may allocate more space to one view than others using the layout_weight tag [^].

  • RelativeLayout - places child views in relative positions. The position of each view can be specified as relative to other elements (e.g. the left-of, above, align-baseline to another view) or in positions relative to the parent area (e.g. aligned to the bottom, left, center) [^].

  • FrameLayout - is designed to block out an area on the screen to display a single item. It should be used to hold a single child view, because it can be difficult to organize child views in a way that's scalable to different screen sizes without the children overlapping each other [^].

  • TableLayout - arranges its children into rows and columns. A TableLayout consists of a number of TableRow objects, each defining a row. Each row has zero or more cells; each cell can hold one View object. The table has as many columns as the row with the most cells. A table can leave cells empty. Cells can span columns, as they can in HTML [^].

  • ListView - displays a scrollable list of items. The list items are automatically inserted to the list using an Adapter that pulls content from a source such as an array or database query and converts each item result into a view that's placed into the list [^].

  • GridView - displays items in a two-dimensional scrollable grid. The grid items are automatically inserted to the layout using a ListAdapter [^].

You may read more about layouts online.

Fig.2.

There are various input methods in Android apps, provided by so called input controls. To name some of them, there are: buttons, text fields (edittext), checkboxes, radio buttons, toggle buttons, spinners, pickers. You may read more about input controls online.

Below you are given an example of the Hello Android layout xml file from last time. You may copy-paste it in your own project. Notice some of the key elements in the xml:

  • The parent layout is a relative layout.

  • It contains a linear layout, a text view and a button.

  • The linear layout has a horizontal orientation and contains one edittext and a button.

  • The linear layout defines its width as match_parent but its height as wrap_content. What is the difference?

  • The edittext has a hint ("Your name") and special text style, making the text appear as bold and italic. The button's displayed text is "Say hello", and it defines a blue (#0000FF) textcolor.

  • Both the edittext and button would occupy the same horizontal space (i.e. 50%) in the linear layout, but the two elements define different layout weights: 3 and 1, making the edittext occupy more horizontal space.

  • By what rule is the linear layout placed on the screen? Notice the above tag.

  • Next, you find a textview defined called tName, centered in the parent (on the screen), with a top margin towards the above linear layout, a light gray background color, with a centered text (gravity), and a larger than normal text size (20sp).

  • Below, you will find a button called bRandom. Where is it placed on the screen?

Layout example

<RelativeLayout

xmlns:android="http://schemas.android.com/apk/res/android"

xmlns:tools="http://schemas.android.com/tools"

android:layout_width="match_parent"

android:layout_height="match_parent"

android:paddingBottom="@dimen/activity_vertical_margin"

android:paddingLeft="@dimen/activity_horizontal_margin"

android:paddingRight="@dimen/activity_horizontal_margin"

android:paddingTop="@dimen/activity_vertical_margin"

tools:context=".MainActivity">

<LinearLayout

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:layout_above="@+id/tName"

android:orientation="horizontal">

<EditText

android:id="@+id/eName"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:layout_weight="3"

android:hint="Your name"

android:textStyle="bold|italic"/>

<Button

android:id="@+id/bClick"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:layout_weight="1"

android:onClick="clicked"

android:text="Say hello"

android:textColor="#0000ff"/>

</LinearLayout>

<TextView

android:id="@+id/tName"

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:layout_centerInParent="true"

android:layout_marginTop="@dimen/activity_vertical_margin"

android:background="#eeeeee"

android:gravity="center_horizontal"

android:text="Hello there"

android:textSize="20sp"/>

<Button

android:id="@+id/bRandom"

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:layout_alignParentBottom="true"

android:onClick="clicked"

android:text="Randomize"/>

</RelativeLayout>

Material design elements

Newer, more advanced views were included in the new design support library offered by Google in 2015. It brings a lot of new material design elements. All hyped about the term material design but have no idea what it actually means? No problem, you can read about it here. To put it simple, it's a new UI design pattern proposed by Google, making graphical elements look simpler, flatter and have a more uniform look across platforms and devices.

New elements include: floating action button (fab), tab layout, snackbar, text input layout, coordinator layout, vector drawables etc. To be able to instantiate these items in your xml and Java code, make sure you add the following dependency to your project's build.gradle file. This example adds support for card views, recycler views and general purpose material design widgets:

dependencies {

compile 'com.android.support:cardview-v7:23.0.+'

compile 'com.android.support:recyclerview-v7:23.0.+'

compile 'com.android.support:design:23.0.+'

}

Note that floating actions buttons, or simply fabs, don't use regular icon images, but need a single color flat type of image; many icons can be found here for free. Consequently, you will be able to add, say, a floating action button in your layout xml as such:

<android.support.design.widget.FloatingActionButton

android:id="@+id/fabSettings"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:clickable="true"

android:src="@drawable/ic_settings"

app:fabSize="mini"/>

A full description of these widgets, and how to include them in your code here.

Task #1

  • Add a popup window with the same greeting text when you click the bClick button. See dialogs in the online Android documentation for implementation details.

  • Add a positive and negative button to your dialog and toast a message on the screen based on which option you click. See dialog builder and Toast in the online documentation.

  • If running your app on a smartphone, try rotating the phone from portrait to landscape. You can rotate the emulator with Ctrl+F6. Does the layout still look the same?

  • Add a Spinner to the layout and populate it with a list of color names. Whenever you select one item from the spinner (color name), the text color of bClick should change accordingly. You will need to use an ArrayAdapter, OnItemSelectedListener listener, and a Map<,> for this.

Intents and starting implicit actions

An intent is an abstract description of an operation to be performed. It can be used with startActivity to launch an Activity, broadcastIntent to send it to any interested BroadcastReceiver components, and startService or bindService to communicate with a background Service.

An Intent provides a facility for performing runtime binding between the code in different applications. Its most significant use is in the launching of activities, where it can be thought of as the bridge between activities. It is basically a passive data structure holding an abstract description of an action to be performed. Within intent we may pass data that is otherwise inaccessible from one activity to another.

There are two types of intents:

  • Explicit intents specify the component to start by name (the fully-qualified class name, like SecondActivity.class). You'll typically use an explicit intent to start a component in your own app, because you know the class name of the activity or service you want to start. In the example below we start activity Test1 as a response to a button click. To do so, we first create a new intent with the defined destination (Test1.class), and add extra information to pass along to the next activity. As there are no references of currently existing activities accessible from one activity to another, there are three usual ways to pass information along: using an Intent extra, using the Bundle, or using a custom made singleton class which holds the "state" of the application. In this example we add two string extras defined under the keys KEY_NAME and KEY_PASS. These are stored in a dictionary and will be available under the same keys once the next activity receives the intent in its onCreate method.

private static final String KEY_NAME = "key_name";

private static final String KEY_PASS = "key_password";

public void clicked(View view) {

Intent intent = new Intent(this, Test1.class);

intent.putExtra(KEY_NAME, "user name");

intent.putExtra(KEY_PASS, "some password");

startActivity(intent);

}

  • Implicit intents do not name a specific component, but instead declare a general action to perform, which allows a component from another app to handle it. For example, if you want to show the user a location on a map, you can use an implicit intent to request that another capable app show a specified location on a map. Let's say you have content (text) you want the user to share with other people. Like in the example below, simply create an intent with the ACTION_SEND action and add extras that specify the content to share. When you call startActivity with that intent, the user can pick an app through which to share the content. It's possible that a user won't have any apps that handle the implicit intent you send to startActivity. If that happens, the call will fail and your app will crash. To verify that an activity will receive the intent, call resolveActivity on your Intent object. When there is more than one app that responds to your implicit intent, the user can select which app to use and make that app the default choice for the action. This is nice when performing an action for which the user probably wants to use the same app from now on, such as when opening a web page (users will select their preferred browser).

public void shareText(String text) {

// Create the text message with a string

Intent sendIntent = new Intent();

sendIntent.setAction(Intent.ACTION_SEND);

sendIntent.putExtra(Intent.EXTRA_TEXT, text);

sendIntent.setType("text/plain");

// Verify that the intent will resolve to an activity

if (sendIntent.resolveActivity(getPackageManager()) != null) {

startActivity(sendIntent);

}

}

Task #2

  • Add two new buttons underneath the textview tName: bShare and bSearch. Make them fit the horizontal space evenly.

  • When the bShare button is clicked, you should create an implicit intent with ACTION_SEND to share the user input from eName using the apps available on the phone. Show a list of all available apps using a chooser intent. See documentation on intents here.

  • When the bSearch button is clicked, you should create an implicit intent with ACTION_VIEW to open the default web browser and perform a google search of the user input. Note: this intent requires a valid Url, so you cannot directly pass the user text to it. See how google search accepts parameters in its url.

  • For extra experience, use floating action buttons aligned in the bottom right corner of the screen, instead of the two regular share and search buttons.

Have a fruitful week.

Rambutan fruit

Rambutan fruit is naturally red in color but they sometimes seem like yellow or orange. 'Rambut' is a malay word which means “hair”, hence it got its name because of the Thorn like appearance. The shape of Rambutan fruit is round or oval and it is upto three to six to four cm in dimension. Rambutan is borne in clusters. Its leather like skin has flexible thorns. It has brownish seed with two to three cm in size and is basally scarred. It is soft and crusty.

http://www.fruitsinfo.com/Rambutan-fruit.php