0% found this document useful (0 votes)
5 views11 pages

Attachment 1

Uploaded by

sreenu_pes
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views11 pages

Attachment 1

Uploaded by

sreenu_pes
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 11

Week 4 Instructor’s Notes

// My instructions and comments are in red text – not all sections of the tutorial are
copied/pasted/annotated in this document, so have the tutorial Web pages open.
// Remember: When you see the word “class” this means Java
// Important: At least after each major section of the tutorial, try to run your project (this
will build your project) so that you catch errors early and can fix them as you go along.
Do not wait until the end of the tutorial to do a build; it will be much harder to identify
and fix errors.
// One problem I had when running the app was seeing the Toolbar with text and icons. I fixed
this by editing my layout files in Design mode, selecting the Toolbar, then in Properties:
1. Select background

2. Access Resources pallet


3. System/holo_blue_dark (able to see both black and white easily on this color)
There are other ways you can set the colors of the Toolbar.
// Make sure you READ the tutorial – understand what you are doing, do not just put the
code together

Add a Toolbar to an Activity


These steps describe how to set up a Toolbar as your activity's app bar:
1. Add the v7 appcompat support library to your project, as described in Support Library Setup.
When you open MainActivity.java, the import statements look like this:

Click the … to expand and see the imports. An import statement imports Android packages,
which are sets of Android class files. You can write an import statement to import a single class
file. When you expand the import statements, you will see that the AppCompatActivity class is
already imported, which is why there is no error thrown on the class statement in Step 2.

2. Make sure the activity extends AppCompatActivity:

public class MyActivity extends AppCompatActivity {


// ... You should have this by default
}

Note: Make this change for every activity in your app that uses a Toolbar as an app bar.

3. In the app manifest, set the <application> element to use one of


appcompat's NoActionBar themes. Using one of these themes prevents the app from using the
native ActionBar class to provide the app bar. For example:
<application
android:theme="@style/Theme.AppCompat.Light.NoActionBar"
/> Replace the default theme in the manifest file with this theme

4. Add a Toolbar to the activity's layout. For example, the following layout code adds a Toolbar and
gives it the appearance of floating above the activity:

<android.support.v7.widget.Toolbar
android:id="@+id/my_toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
android:elevation="4dp"
android:theme="@style/ThemeOverlay.AppCompat.ActionBar"
app:popupTheme="@style/ThemeOverlay.AppCompat.Light"/>
// Add this code to activity_main.xml – this code tells your app to use a Toolbar
object. When you first put this code in, you will get the following error:

// This error appears because there is no identifier for ‘app’. Do what the blue
popup tells you: Press Alt+Enter. Android Studio adds a line of code which
defines ‘app’ as an attribute to the layout’s RelativeLayout tag:

// If you run your app and the toolbar does not stretch all the way across your
screen, then in the code aobve, remove the padding attributes(these attributes add
space between widgets).

The Material Design specification recommends that app bars have an elevation of 4 dp.
Position the toolbar at the top of the activity's layout, since you are using it as an app bar.
This means the Toolbar tag and attirbutes must be before any other elements in your layout file
but remember the root tag of the layout file is the layout type (RelativeLayout) so the Toolbar
must be second in the layout file and indented one level.
5. In the activity's onCreate() method (in MainActivity.java), call the
activity's setSupportActionBar() method, and pass the activity's toolbar. This method sets the
toolbar as the app bar for the activity. For example: (add the two lines in the red box)

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my);
Toolbar myToolbar = (Toolbar) findViewById(R.id.my_toolbar);
setSupportActionBar(myToolbar);
}
When you first add these two lines, you will get an error because there is no Java
definition for the Toolbar class:

Again, press Alt+Enter – you will get popups asking what you want to import.
Import the v7 widget Toolbar class –in your import statements you should see:

import android.support.v7.widget.Toolbar;

Here is what the two lines of code added do:

1. The left side of the first line declares a reference for a Toolbar object
named “myToolbar”. On the right side of the = sign, a new Toolbar object is
created (instantiated) using the Toolbar definition that you provided in
your layout file. The Toolbar object is assigned to the myToolbar
reference.
2. The second line sets the Toolbar to be your ActionBar. This means that the
Toolbar will be able to use ActionBar methods (read the first two
paragraphs under Use App Bar Utility Methods).
Your app now has a basic action bar. By default, the action bar contains just the name of the app
and an overflow menu. The options menu initially contains just the Settings item. You can add more
actions to the action bar and the overflow menu, as described in Adding and Handling Actions.

Add Action Buttons


All action buttons and other items available in the action overflow are defined in an XML menu
resource. To add actions to the action bar, create a new XML file in your
project's res/menu/ directory.

1. Under the res folder, add a menu folder


2. In the menu folder, add a file named ‘menu_main.xml’
Add an <item> element for each item you want to include in the action bar, as shown in this code
example of a menu XML file:

3. Add the following code to your menu_main.xml file:

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

<!-- "Mark Favorite", should appear as action button if possible -->


<item
android:id="@+id/action_favorite"
android:icon="@drawable/ic_favorite_black_48dp"
android:title="@string/action_favorite"
app:showAsAction="ifRoom"/>

<!-- Settings, should always be in the overflow -->


<item android:id="@+id/action_settings"
android:title="@string/action_settings"
app:showAsAction="never"/>

</menu>

// When you first add this code you will get the following errors because: 1) Your
project does not have a set of graphics for the favorite icon you are trying to add
to the Toolbar, and 2) you do not have string definitions for your favorite action or
your settings action.
// To fix the missing graphics problem, refer to my Week 2 Instructor’s Notes, the
section on Create Different Bitmaps, and from the Material Icons page, select the

favorite icon: When adding the icons, you must name the icons the same as
in this line: android:icon="@drawable/ic_favorite_black_48dp"
You are also going to need a search icon for later in the tutorial, so go back to

Material Icons and get the search icon; name it “ic_action_search.png”

To fix the string errors, add strings to res/values/strings.xml for action_favorite


and action_settings (the strings can display any text that you want, but they must be
defined). The string name attributes must be the same as in the menu_main.xml file.
You will know the errors are fixed when the code turns from red to green.

The app:showAsAction attribute specifies whether the action should be shown as a button on the
app bar. If you set app:showAsAction="ifRoom" (as in the example code's favorite action), the
action is displayed as a button if there is room in the app bar for it; if there is not enough room,
excess actions are sent to the overflow menu. If you set app:showAsAction="never" (as in the
example code's settings action), the action is always listed in the overflow menu, not displayed in the
app bar.
The system uses the action's icon as the action button if the action is displayed in the app bar. You
can find many useful icons on the Material Iconspage.
Respond to Actions
When the user selects one of the app bar items, the system calls your
activity's onOptionsItemSelected() callback method, and passes a MenuItemobject to indicate
which item was clicked. In your implementation of onOptionsItemSelected(), call
the MenuItem.getItemId() method to determine which item was pressed. The ID returned matches
the value you declared in the corresponding <item> element's android:id attribute.

For example, the following code checks to see which action the user selected. If the method does
not recognize the user's action, it invokes the superclass method:

// Add the following code to your MainActivity class below the onCreate() method but
before the closing brace } of the MainActivity class.
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_settings:
// User chose the "Settings" item, show the app settings UI...
return true;
case R.id.action_favorite:
// User chose the "Favorite" action, mark the current item
// as a favorite...
return true;
default:
// If we got here, the user's action was not recognized.
// Invoke the superclass to handle it.
return super.onOptionsItemSelected(item);

}
}

Adding an Up Action
Your app should make it easy for users to find their way back to the app's main screen.
One simple way to do this is to provide an Up button on the app bar for all activities
except the main one. When the user selects the Up button, the app navigates to the
parent activity.

This lesson shows you how to add an Up button to an activity by declaring the activity's parent in the
manifest, and enabling the app bar's Up button.

Declare a Parent Activity


To support the up functionality in an activity, you need to declare the activity's parent. You can do
this in the app manifest, by setting an android:parentActivityName attribute.

The android:parentActivityName attribute was introduced in Android 4.1 (API level 16). To
support devices with older versions of Android, define a<meta-data> name-value pair, where the
name is "android.support.PARENT_ACTIVITY" and the value is the name of the parent activity.
For example, suppose your app has a main activity named MainActivity and a single child activity.
The following manifest code declares both activities, and specifies the parent/child relationship:

<application ... >


...

// Add the code highlighted in gray to your manifest file. You will need to make
// some changes to this code; I describe the changes below.

<!-- The main/home activity (it has no parent activity) -->

<activity
android:name="com.example.myfirstapp.MainActivity" ...>
...
</activity>

<!-- A child of the main activity -->


<activity
android:name="com.example.myfirstapp.MyChildActivity"
android:label="@string/title_activity_child"
android:parentActivityName="com.example.myfirstapp.MainActivity" >

<!-- Parent activity meta-data to support 4.0 and lower -->


<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value="com.example.myfirstapp.MainActivity" />
</activity>
</application>

First change: In the block of code below (reference to your parent activity), your
project’s package name and project name must be in front of MainActivity. If your
package name is “com.example.myfirstapp”, then leave it. You can shorten up this
little block of code to one line of code as well. The three dots must be deleted, in
both spots.

<activity
android:name="com.example.myfirstapp.MainActivity" ...>
...
</activity>

In my project, I have changed the block above to what you see below. Note that my
package name and project name are different, and I shortened the code to one line.

<!-- The main/home activity (it has no parent activity) -->

When you edit this line of code, if you get a red wavy line under it as shown above,
this means the main activity is being declared twice, which is an error. If there is
an activity element already in your application element that declares your main
activity (see block below), then delete the two lines of code above this paragraph:
Second change: The block of code below was copied straight from the tutorial and
pated into my project – note the errors. You have to hover over the ~ to see the
popup error message:

Here is my fixed code:

I made the following changes:


 Replaced the package.project name
 Added a string to values/strings.xml for this line:
android:label="@string/title_activity_child"
My strings.xml file currently looks like this:
Question: What happens if you delete the @ symbol from this string:
android:label="@string/title_activity_child"
 The error described by the “Element activity is not closed” popup is actually
caused by a code error in the tutorial; it is simple to fix – I added a / to
provide a properly-formed closing tag for the activity element.
 I still have an error. Why is MyChildActivity red?

android:name="com.john.week4assignment.MyChildActivity"

Because I have not yet added the Java class MyChildActivity to the project:

1. Navigate to app/source/main/java/<your_package_name.your_project_name>
2. Right-click, New > Java Class
3. Name the class MyChildActivity, click OK
4. You should get this template and you should see the file added under
app/source/main/java/<your_package_name.your_project_name>:

5. In the manifest, you will see an error, “… MyChildActivity is not


assignable to ‘android.app.Activity’”, but this error will go away after
code for the application is added to the child class.

Enable the Up Button (This will be an action view)


To enable the Up button for an activity that has a parent activity, call the app
bar's setDisplayHomeAsUpEnabled() method. Typically, you would do this when the activity is
created. For example, the following onCreate() method sets a Toolbar as the app bar
for MyChildActivity, then enables that app bar's Up button:

// This code goes in MyChildActivity.java


// Remember that you are going to see errors after you add the code until you import
// all of the packages necessary to support the objects used in the code.
// First fix class declaration: public class MyChildActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my_child); // Must add layout for child class

// my_child_toolbar is defined in the layout file


Toolbar myChildToolbar =
(Toolbar) findViewById(R.id.my_child_toolbar); // Add Toolbar in child layout
setSupportActionBar(myChildToolbar);

// Get a support ActionBar corresponding to this toolbar


ActionBar ab = getSupportActionBar();

// Enable the Up button


ab.setDisplayHomeAsUpEnabled(true);
}

You do not need to catch the up action in the activity's onOptionsItemSelected() method. Instead,
that method should call its superclass, as shown inRespond to Actions. The superclass method
responds to the Up selection by navigating to the parent activity, as specified in the app manifest.

Add an Action View


To add an action view, create an <item> element in the toolbar's menu resource, as Add Action
Buttons describes. Add one of the following two attributes to the <item> element:

 actionViewClass: The class of a widget that implements the action.

 actionLayout: A layout resource describing the action's components.

Set the showAsAction attribute to


either "ifRoom|collapseActionView" or "never|collapseActionView" .
The collapseActionView flag indicates how to display the widget when the user is not interacting
with it: If the widget is on the app bar, the app should display the widget as an icon. If the widget is in
the overflow menu, the app should display the widget as a menu item. When the user interacts with
the action view, it expands to fill the app bar.

For example, the following code adds a SearchView widget to the app bar:

// This code goes into menu_main.xml


// When you paste it, you will get two errors, but you should know how to fix them
<item android:id="@+id/action_search"
android:title="@string/action_search"
android:icon="@drawable/ic_search"
app:showAsAction="ifRoom|collapseActionView"
app:actionViewClass="android.support.v7.widget.SearchView" />
If the user is not interacting with the widget, the app displays the widget as the icon specified
by android:icon. (If there is not enough room in the app bar, the app adds the action to the
overflow menu.) When the user taps the icon or menu item, the widget expands to fill the toolbar,
allowing the user to interact with it.

// At this point, when you run your app, you


should see the screen for the main activity (top
screen, and whatever you named your app), and
when you click the search icon, you should
navigate to the second screen (bottom screen),
but you will not see the message send function
because there is no code for it yet.

Clicking the Up icon (left-pointing arrow) should


take you back to the main activity screen.

In the main activity screen, the favorites icon


does not do anything, but you can access the
overflow area (3 vertical dots).
Figure 1. When the user clicks an action view's icon, the view's UI fills the toolbar.

// STOP HERE

You might also like