Lab Exercise 05

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 10

BGIT 4317 | Mobile Programming Course

Lab Exercise 05
Introduction
His practical introduces tab navigation, in which tabs appear across the top of a screen,
providing navigation to other screens. Tab navigation is a popular way to create lateral
navigation from one child screen to a sibling child screen, as shown in the figure below.

In the figure above:

1. Lateral navigation from one category screen (Top Stories, Tech News, and Cooking) to
another
2. Lateral navigation from one story screen (Story) to another

With the tabs, the user can navigate to and from the sibling screens without navigating up to the
parent screen. Tabs can also provide navigation to and from stories, which are sibling screens
under the Top Stories parent.

What you'll learn


 How to set up an app with tab navigation and swipe views.

What you'll do
 Create a new app with tabs for navigating Activity screens that can also be swiped.

1
BGIT 4317 | Mobile Programming Course

You will also create an app for tab navigation that shows three tabs below the app bar to navigate
to sibling screens. When the user taps a tab, the screen shows a content screen, depending on
which tab the user tapped. The user can also swipe left and right to visit the content screens.
The ViewPager class automatically handles user swipes to screens or View elements.

3. Task 2: Use tab navigation with swipe views


With lateral navigation, you enable the user to go from one sibling to another (at the same level
in a multitier hierarchy). For example, if your app provides several categories of stories (such
as Top Stories, Tech News, and Cooking, as shown in the figure below), you would want to
provide your users the ability to navigate from one category to the next, without having to
navigate back up to the parent screen. Another example of lateral navigation is the ability to
swipe left or right in a Gmail conversation to view a newer or older one in the same Inbox.

2
BGIT 4317 | Mobile Programming Course

2.1 Create the project and layout


1. Create a new project using the Empty Activity template. Name the app Tab Experiment.
2. Edit the build.gradle (Module: app) file, and add the following line to
the dependencies section for the Android Design Support Library, which you need in
order to use a TabLayout:
implementation 'com.android.support:design:26.1.0'

If Android Studio suggests a version with a higher number, edit the line above to update the
version.

3. In order to use a Toolbar rather than an app bar and app title, add the following attributes
to the res > values > styles.xml file to hide the app bar and the title:
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
<!-- Other style attributes -->
<item name="windowActionBar">false</item>
<item name="windowNoTitle">true</item>
</style>

4. Open activity_main.xml layout file, and click the Text tab to view the XML code.
5. Change the ConstraintLayout to RelativeLayout, as you've done in previous exercises.
6. Add the android:id attribute and android:padding of 16dp to the RelativeLayout.
7. Remove the TextView supplied by the template, and add a Toolbar, a TabLayout, and
a ViewPager within the RelativeLayout as shown in the code below.
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="16dp"
tools:context="com.example.android.tabexperiment.MainActivity">

<android.support.v7.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:background="?attr/colorPrimary"
android:minHeight="?attr/actionBarSize"

3
BGIT 4317 | Mobile Programming Course

android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
app:popupTheme="@style/ThemeOverlay.AppCompat.Light"/>

<android.support.design.widget.TabLayout
android:id="@+id/tab_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@id/toolbar"
android:background="?attr/colorPrimary"
android:minHeight="?attr/actionBarSize"
android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"/>

<android.support.v4.view.ViewPager
android:id="@+id/pager"
android:layout_width="match_parent"
android:layout_height="fill_parent"
android:layout_below="@id/tab_layout"/>

</RelativeLayout>

As you enter the app:popupTheme attribute for Toolbar, app will be in red if you didn't add
the following statement to RelativeLayout:

<RelativeLayout xmlns:app="http://schemas.android.com/apk/res-auto"

You can click app and press Option+Enter (or Alt+Enter), and Android Studio automatically
adds the statement.

2.2 Create a class and layout for each fragment


To add a fragment representing each tabbed screen, follow these steps:

1. Click com.example.android.tabexperiment in the Android > Project pane.


2. Choose File > New > Fragment > Fragment (Blank).
3. Name the fragment TabFragment1.
4. Select the Create layout XML? option.
5. Change the Fragment Layout Name for the XML file to tab_fragment1.
6. Clear the Include fragment factory methods? option and the Include interface
callbacks? option. You don't need these methods.
7. Click Finish.

4
BGIT 4317 | Mobile Programming Course

Repeat the steps above, using TabFragment2 and TabFragment3 for Step 3,
and tab_fragment2 and tab_fragment3 for Step 4.

Each fragment is created with its class definition set to extend Fragment. Also,
each Fragment inflates the layout associated with the screen
(tab_fragment1, tab_fragment2, and tab_fragment3), using the familiar resource-inflate
design pattern you learned in a previous chapter with the options menu.

For example, TabFragment1 looks like this:

public class TabFragment1 extends Fragment {

public TabFragment1() {
// Required empty public constructor
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment.
return inflater.inflate(R.layout.tab_fragment1, container, false);
}

2.3 Edit the fragment layout


Edit each Fragment layout XML file (tab_fragment1, tab_fragment2, and tab_fragment3):

1. Change the FrameLayout to RelativeLayout.


2. Change the TextView text to "These are the top stories: " and
the layout_width and layout_height to wrap_content.
3. Set the text appearance
with android:textAppearance="?android:attr/textAppearanceLarge" .

Repeat the steps above for each fragment layout XML file, entering different text for
the TextView in step 2:

 Text for the TextView in tab_fragment2.xml: "Tech news you can use: "
 Text for the TextView in tab_fragment3.xml: "Cooking tips: "

Examine each fragment layout XML file. For example, tab_fragment1 should look like this:

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

5
BGIT 4317 | Mobile Programming Course

xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.android.tabexperiment.TabFragment1">

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="These are the top stories: "
android:textAppearance="?android:attr/textAppearanceLarge"/>

</RelativeLayout>

4. In the Fragment layout XML file tab_fragment1, extract the string for "These are
the top stories:" into the string resource tab_1. Do the same for the strings
in tab_fragment2, and tab_fragment3.

2.3 Add a PagerAdapter


The adapter-layout manager pattern lets you provide different screens of content within
an Activity:

 Use an adapter to fill the content screen to show in the Activity.


 Use a layout manager that changes the content screens depending on which tab is
selected.

Follow these steps to add a new PagerAdapter class to the app that
extends FragmentStatePagerAdapter and defines the number of tabs (mNumOfTabs):

1. Click com.example.android.tabexperiment in the Android > Project pane.


2. Choose File > New > Java Class.
3. Name the class PagerAdapter, and enter FragmentStatePagerAdapter into the
Superclass field. This entry changes
to android.support.v4.app.FragmentStatePagerAdapter .
4. Leave the Public and None options selected, and click OK.
5. Open PagerAdapter in the Project > Android pane. A red light bulb should appear next
to the class definition. Click the bulb and choose Implement methods, and then
click OK to implement the already selected getItem() and getCount() methods.
6. Another red light bulb should appear next to the class definition. Click the bulb and
choose Create constructor matching super.

6
BGIT 4317 | Mobile Programming Course

7. Add an integer member variable mNumOfTabs, and change the constructor to use it.
The code should now look as follows:
public class PagerAdapter extends FragmentStatePagerAdapter {
int mNumOfTabs;

public PagerAdapter(FragmentManager fm, int NumOfTabs) {


super(fm);
this.mNumOfTabs = NumOfTabs;
}

/**
* Return the Fragment associated with a specified position.
*
* @param position
*/
@Override
public Fragment getItem(int position) {
return null;
}

/**
* Return the number of views available.
*/
@Override
public int getCount() {
return 0;
}
}

While entering the code above, Android Studio automatically imports the following:

import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;

If FragmentManager in the code is in red, a red light bulb icon should appear when you click
it. Click the bulb icon and choose Import class. Import choices appear.
Select FragmentManager (android.support.v4).

8. Change the newly added getItem() method to the following, which uses a switch
case block to return the Fragment to show based on which tab is clicked:

@Override
public Fragment getItem(int position) {

7
BGIT 4317 | Mobile Programming Course

switch (position) {
case 0: return new TabFragment1();
case 1: return new TabFragment2();
case 2: return new TabFragment3();
default: return null;
}
}

9. Change the newly added getCount() method to the following to return the number of
tabs:
@Override
public int getCount() {
return mNumOfTabs;
}

2.4 Inflate the Toolbar and TabLayout


Because you are using tabs that fit underneath the app bar, you have already set up the app bar
and Toolbar in the activity_main.xml layout in the first step of this task. Now you need to
inflate the Toolbar (using the same method described in a previous chapter about the options
menu), and create an instance of TabLayout to position the tabs.

1. Open MainActivity and add the following code inside the onCreate() method to inflate
the Toolbar using setSupportActionBar():
protected void onCreate(Bundle savedInstanceState) {
// ... Code inside onCreate() method
android.support.v7.widget.Toolbar toolbar =
findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
// Create an instance of the tab layout from the view.
}

2. Open strings.xml, and create the following string resources:


<string name="tab_label1">Top Stories</string>
<string name="tab_label2">Tech News</string>
<string name="tab_label3">Cooking</string>

3. At the end of the onCreate() method, create an instance of the tab layout from
the tab_layout element in the layout, and set the text for each tab using addTab():
// Create an instance of the tab layout from the view.
TabLayout tabLayout = findViewById(R.id.tab_layout);
// Set the text for each tab.

8
BGIT 4317 | Mobile Programming Course

tabLayout.addTab(tabLayout.newTab().setText(R.string.tab_label1));
tabLayout.addTab(tabLayout.newTab().setText(R.string.tab_label2));
tabLayout.addTab(tabLayout.newTab().setText(R.string.tab_label3));
// Set the tabs to fill the entire layout.
tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
// Use PagerAdapter to manage page views in fragments.

2.5 Use PagerAdapter to manage screen views


1. Below the code you added to the onCreate() method in the previous task, add the
following code to use PagerAdapter to manage screen (page) views in the fragments:
// Use PagerAdapter to manage page views in fragments.
// Each page is represented by its own fragment.
final ViewPager viewPager = findViewById(R.id.pager);
final PagerAdapter adapter = new PagerAdapter
(getSupportFragmentManager(), tabLayout.getTabCount());
viewPager.setAdapter(adapter);
// Setting a listener for clicks.

2. At the end of the onCreate() method, set a listener


( TabLayoutOnPageChangeListener) to detect if a tab is clicked, and create
the onTabSelected() method to set the ViewPager to the appropriate tabbed screen.
The code should look as follows:
// Setting a listener for clicks.
viewPager.addOnPageChangeListener(new
TabLayout.TabLayoutOnPageChangeListener(tabLayout));
tabLayout.addOnTabSelectedListener(new
TabLayout.OnTabSelectedListener() {
@Override
public void onTabSelected(TabLayout.Tab tab) {
viewPager.setCurrentItem(tab.getPosition());
}

@Override
public void onTabUnselected(TabLayout.Tab tab) {
}

@Override
public void onTabReselected(TabLayout.Tab tab) {
}
});

9
BGIT 4317 | Mobile Programming Course

3. Run the app. Tap each tab to see each "page" (screen). You should also be able to swipe
left and right to visit the different "pages".

10

You might also like