0% found this document useful (0 votes)
1 views76 pages

Android 2 Android With Menus

The document outlines a course on Android development focusing on creating applications with menus, including navigation drawers and activity selection. It provides tutorials, code snippets, and project guidelines for implementing menus in Android apps. Additionally, it discusses best practices for managing menu options across multiple activities using a base class approach.

Uploaded by

vicentselfa
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)
1 views76 pages

Android 2 Android With Menus

The document outlines a course on Android development focusing on creating applications with menus, including navigation drawers and activity selection. It provides tutorials, code snippets, and project guidelines for implementing menus in Android apps. Additionally, it discusses best practices for managing menu options across multiple activities using a base class approach.

Uploaded by

vicentselfa
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/ 76

IES Jaume II el Just

Tavernes de la Valldigna

Mobile
development

Vicent Selfa
Curs 2020/2021
Android
with menus

Android developer
Android

● Interesting links
● A menu for selecting activities
● A project with menus
● The complete project here
● The My Adapters project using a menu.
● Navigation Drawer menu
● A drawer menu with Android Studio 3.5.1
● Annex: Tabbed activity
● Annex: Other kind of menus
Android

● Interesting links
Tutorials:
• Android tutorial
This tutorial will teach you basic Android programming and will also
take you through some advance concepts related to Android application
development.
• Curso de programación Android
Con el Curso de Programación en Android de sgoliver.net aprenderás a
crear desde cero tus propias aplicaciones para dispositivos móviles
con sistema operativo Android.

Video: Android and Android Studio: Getting Started


Learn how to get started with Android and Android Studio in this short tutorial.
It demonstrates how to install Android Studio (Google’s official Android IDE)
and create your first Android app.

Android APP development:


A complete guide about Android APP development
Android

A menu for selecting activities:


Basic Activity
Android
A menu for selecting activities: The activities
Android
A menu for selecting activities:
Forgetting the fragments … for the moment
Commenting the fragment layout
Android
A menu for selecting activities:
Forgetting the fragments … for the moment
Deleting unnecessary files

.
Android
A menu for selecting activities: The MainActivity
MainActivity.java
public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);

FloatingActionButton fab = findViewById(R.id.fab);


fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action",
Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
menu_main, menu);
getMenuInflater().inflate(R.menu.
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();

//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
Android
A menu for selecting activities: The activity_main

activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.coordinatorlayout.widget.CoordinatorLayout
xmlns:android="http://schemas.android.com/apk/res/android"
<!– Other tags --> />

</com.google.android.material.appbar.AppBarLayout>

<include layout="@layout/content_main" />

<com.google.android.material.floatingactionbutton
.FloatingActionButton
android:id="@+id/fab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|end"
android:layout_margin="@dimen/fab_margin"
app:srcCompat="@android:drawable/ic_dialog_email" />

</androidx.coordinatorlayout.widget.CoordinatorLayout>

content_main.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
<!– Other tags --> >

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>
Android
A menu for selecting activities: Adding activities
Android
A menu for selecting activities: Adding options to the menu
<menu 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"
tools:context="com.example.vicent.menuaplicacions.MainActivity">
<item
android:id="@+id/home"
android:title="@string/home"
app:showAsAction="never" />
<item
android:id="@+id/activity1"
android:title="@string/activity1"
app:showAsAction="never" />
<item
android:id="@+id/activity2"
android:title="@string/activity2"
app:showAsAction="never" />
</menu>
menu_main.xml

strings.xml
<resources>
<string name="app_name">Un menu d\'activitats</string>
<string name="text">Try an application from the menu</string>
<string name=“home">Home</string>
<string name="activity1">Activity 1</string>
<string name="activity2">Activity 2</string>
</resources>
Android
A menu for selecting activities:
Adding methods for managing menus
MainActivity.java
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.home) {
Intent intent = new Intent(this, MainActivity.class);
startActivity(intent);
}
if (id == R.id.activity1) {
Intent intent = new Intent(this, Main1Activity.class);
startActivity(intent);
}
if (id == R.id.activity2) {
Intent intent = new Intent(this, Main2Activity.class);
startActivity(intent);
}
return super.onOptionsItemSelected(item);
}

Exercise: Add similar methods onCreateOptionsMenu and


onOptionsItemSelected to the other two activities
Android
A menu for selecting activities: The Android manifest file
AndroidManifest.xml
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity
android:name=".MainActivity"
android:label="@string/app_name"
android:theme="@style/AppTheme.NoActionBar">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".Main1Activity"
android:label="@string/title_activity_main1"
android:theme="@style/AppTheme.NoActionBar" />
<activity
android:name=".Main2Activity"
android:label="@string/title_activity_main2"
android:theme="@style/AppTheme.NoActionBar" />
</application>
Android
A menu for selecting activities: The final result

One problem: Every new option in the menu has to be added into every
activity!!!
Android
A menu for selecting activities: The MainMenu class
Improve the previous version using only ONE MainMenu.java class and
inherit this into the other Activities.

public class MainMenu extends AppCompatActivity {

}
Android
A menu for selecting activities: The final result
Cut the onCreateOptionsMenu and onOptionsItemSelected from the
activities and add them into the MainMenu class.

public class MainMenu extends AppCompatActivity {

@Override
public boolean onCreateOptionsMenu(Menu menu) { //TODO}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
//TODO
}
}
MainMenu.java
public class MainActivity extends MainMenu {
@Override
protected void onCreate() {
// This is the only one method into the activities
}
}
MainActivity, Main1Activity, Main2Activity classes
Android
A menu for selecting activities: The final result
Android
A project with menus
Create a new Android Studio project using the Basic Activity
Android

A project with menus


Android
A project with menus
Take a look to the MainActivity class and look for the new methods added
to control the menu options.

MainActivity.java
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
}

More information about menus here:


Android
A project with menus
Take a look to the activity_main.xml and content_main.xml files

activity_main.xml
<android.support.design.widget.CoordinatorLayout
<!– More code 🡪
<include layout="@layout/content_main" />
<!– More code 🡪
</android.support.design.widget.CoordinatorLayout>

content_main.xml
<android.support.constraint.ConstraintLayout
<!– More code 🡪
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</android.support.constraint.ConstraintLayout>
Android
A project with menus
Create new values resource files
Android
A project with menus
Translating the options of the menus
depending on the Locale configuration

<string name="action_settings"> Settings </string>

<string name="action_settings"> Configuració </string>


Android
A project with menus
ca\strings.xml
<!-- Missatges personalitzats -->
<string name="start">Iniciant aplicació ...</string>
<string name="OK">Acceptar</string>

es\strings.xml
<!-- Missatges personalitzats -->
<string name="start">Iniciando aplicación ...</string>
<string name="OK">Aceptar</string>

// Add the next code into your MainActivity.java file MainActivity.java


// And run the project
String text, inici, ok;
public void onStart() {
super.onStart(); Log.d(tag, "onStart() event");
inici = getString(R.string.start);
ok = getString(R.string.OK);
buildDialog("onStart() action", inici);
displayToast("onStart() action");
}
public void buildDialog (String title, String message) {
// Programed in the previous notes
builder.setPositiveButton(ok,null);
// …
}
Android
A project with menus
Exercise: Show a toast with information about the option selected

MainActivity.java
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
displayToast ("You have choosen the option: "
+ getString(R.string.action_settings));
return true;
}
}
Android
A project with menus
Create a new Java class: MainMenu

MainMenu.java
public class MainMenu extends AppCompatActivity {
// Moved from MainActivity!!!
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu. menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id. action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
Android
A project with menus

Create a new basic activity: ActionOneActivity

public class ActionOneActivity extends MainMenu {


@Override
protected void onCreate(Bundle savedInstanceState) {
// Other code
}
}
ActionOneActivity.java
Android
A project with menus
Add more options to your menu_main file.
menu_main.xml
<item
android:id="@+id/actionOne"
android:title="@string/action_one"
app:showAsAction="never" />
<item
android:id="@+id/home"
android:title="@string/home"
app:showAsAction="never" />

Add new if options into the MainMenu class:

public boolean onOptionsItemSelected(MenuItem item) { MainMenu.java


int id = item.getItemId();
if (id == R.id.action_settings) { eturn true; }
if (id == R.id.actionOne) {
Intent intent = new Intent(this, ActionOneActivity.class);
startActivity(intent);
}
if (id == R.id.home) {
Intent intent = new Intent(this, MainActivity.class);
startActivity(intent);
}
return super.onOptionsItemSelected(item);
}
Android
A project with menus
Check the result

Menu class reference information here:


Android
A project with menus
Annex: Improving the MainMenu class.

Do nothing if you click on the same activity where you are.


MainMenu.java
public class MainMenu extends AppCompatActivity {
// To remember the previous option number, so do nothing if you select it again
static int numOption = 0; // The first option: Home
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu); return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId(); Intent intent;
if (id == R.id. home) {
if (numOption != 0) {
intent = new Intent(this, MainActivity. class);
numOption = 0; startActivity(intent); }
}
if (id == R.id. actionOne) {
if (numOption != 1) {
intent = new Intent(this, ActionOneActivity. class);
numOption = 1; startActivity(intent); }
}
return super.onOptionsItemSelected(item);
}
}
Android
A project with menus
Annex: Improving the MainMenu class.

Hide the option menu of the current activity.


MainMenu.java
public class MainMenu extends AppCompatActivity {
// To remember the previous option number, so hide this menú option
static int numOption = 0; // The first option: Home
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu. menu_main, menu);
// Set visible all the option menus except the current!!
for (int i = 0; i < menu.size(); i++) {
if (i == numOption) menu.getItem(i).setVisible( false);
else menu.getItem(i).setVisible( true);
}
return true;
}
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId(); Intent intent;
if (id == R.id. home) {
numOption = 0; intent = new Intent(this, MainActivity. class);
startActivity(intent); }
if (id == R.id. actionOne) {
numOption = 1; intent = new Intent(this, ActionOneActivity. class);
startActivity(intent); }
return super.onOptionsItemSelected(item);
}
Android
A project with menus
Annex: Improving the MainMenu class.

Hide the option menu of the current activity.


Android
A project with menus
Exercise.- Create a new project (My Adapters with menus), add the
My Adapters activities and reorganize all of them using a menu.
Android
A project with menus
Android

A navigation drawer menu for


selecting activities
Android

A navigation drawer menu for selecting


activities
Android
A navigation drawer menu
Create a new Project using the Navigator Drawer Activity as a template

More info:
Navigation drawer
How to implement navigation drawer in android app?
Android
A navigation drawer menu
The different folders and files of the project

The Controller

The View

The Menus
Android
A navigation drawer menu
The View: The mobile navigation file

mobile_navigation.xml
<navigation 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/mobile_navigation"
app:startDestination="@+id/nav_home">

<fragment
android:id="@+id/nav_home"
android:name="com.example.mynavigationdrawermenuwithas35.ui.home.HomeFragment"
android:label="@string/menu_home"
tools:layout="@layout/fragment_home" />

<fragment
android:id="@+id/nav_gallery"
android:name="com.example.mynavigationdrawermenuwithas35.ui.gallery.GalleryFragment"
android:label="@string/menu_gallery"
tools:layout="@layout/fragment_gallery" />

<!– Other fragments ->

<fragment
android:id="@+id/nav_send"
android:name="com.example.mynavigationdrawermenuwithas35.ui.send.SendFragment"
android:label="@string/menu_send"
tools:layout="@layout/fragment_send" />
</navigation>
Android
A navigation drawer menu
The View: The layout folder

<include
activity_main.xml
layout="@layout/app_bar_main"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<android.support.design.widget.NavigationView
android:id="@+id/nav_view"
<!– More tags … 🡪
app:headerLayout="@layout/nav_header_main"
app:menu="@menu/activity_main_drawer" />

nav_header_main.xml
<LinearLayout
<!– Other tags 🡪
android:background="@drawable/side_nav_bar"

<ImageView
app:srcCompat="@android:drawable/sym_def_app_icon" />

<TextView
android:text="Android Studio"

<TextView
android:text="[email protected]" />

</LinearLayout>
Android
A navigation drawer menu
The Controller: MainActivity.java
MainActivity.java
public class MainActivity extends AppCompatActivity {
private AppBarConfiguration mAppBarConfiguration;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = findViewById(R.id.toolbar); setSupportActionBar(toolbar);
FloatingActionButton fab = findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
DrawerLayout drawer = findViewById(R.id.drawer_layout);
NavigationView navigationView = findViewById(R.id.nav_view);
// Passing each menu ID as a set of Ids because each
// menu should be considered as top level destinations.
mAppBarConfiguration = new AppBarConfiguration.Builder(
R.id.nav_home, R.id.nav_gallery, R.id.nav_slideshow,
R.id.nav_tools, R.id.nav_share, R.id.nav_send)
.setDrawerLayout(drawer) .build();
NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment);
NavigationUI.setupActionBarWithNavController(this, navController, mAppBarConfiguration);
NavigationUI.setupWithNavController(navigationView, navController);
}
// More methods
}
Android
A navigation drawer menu
Calling the view from the controller
MainActivity.java
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main); The view
// More code …

activity_main.xml
<include
layout="@layout/app_bar_main"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<android.support.design.widget.NavigationView
android:id="@+id/nav_view"
<!– More tags … 🡪
app:headerLayout="@layout/nav_header_main"
app:menu="@menu/activity_main_drawer" />

app_bar_main.xml
content _main.xml <include layout="@layout/content_main" />
Android
A navigation drawer menu
Calling the view from the controller
app_bar_main.xml
<include layout="@layout/content_main" />

content _main.xml
<androidx.constraintlayout.widget.ConstraintLayout
<!– more code 🡪
tools:showIn="@layout/app_bar_main">
<fragment
android:id="@+id/nav_host_fragment"
<!– more code 🡪
app:navGraph="@navigation/mobile_navigation" />
</androidx.constraintlayout.widget.ConstraintLayout>
Android
A navigation drawer menu
Calling the view from the controller
activity_main.xml
<include <group android:checkableBehavior="single">
layout="@layout/app_bar_main" <item
android:id="@+id/nav_home"
android:layout_width="match_parent"
android:icon="@drawable/ic_menu_camera"
android:layout_height="match_parent" /> android:title="@string/menu_home" />
<android.support.design.widget.NavigationView <item
android:id="@+id/nav_view" android:id="@+id/nav_gallery"
android:icon="@drawable/ic_menu_gallery"
<!– More tags … 🡪 android:title="Gallery" />
app:headerLayout="@layout/nav_header_main" <item
app:menu="@menu/activity_main_drawer" /> android:id="@+id/nav_slideshow"
android:icon="@drawable/ic_menu_slideshow"
android:title="Slideshow" />
<item
android:id="@+id/nav_manage"
android:icon="@drawable/ic_menu_manage"
android:title="Tools" />
</group>

<item android:title="Communicate">
<menu>
<item
android:id="@+id/nav_share"
android:icon="@drawable/ic_menu_share"
android:title="Share" />
<item
android:id="@+id/nav_send"
android:icon="@drawable/ic_menu_send"
android:title="Send" />
</menu>
</item>
activity_main_drawer.xml
Android
A navigation drawer menu
Calling the different Fragments and ViewModels

Views

Controllers
Android
A navigation drawer menu
Calling the different Fragments and ViewModels

public class HomeFragment extends Fragment { HomeFragment.java


private HomeViewModel homeViewModel;
public View onCreateView( @NonNull LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState)
{
homeViewModel = ViewModelProviders. of(this).get(HomeViewModel. class);
View root = inflater.inflate(R.layout. fragment_home, container,
false);
final TextView textView = root.findViewById(R.id. text_home);
homeViewModel.getText().observe( this, new Observer<String>() {
@Override
public void onChanged( @Nullable String s) { textView .setText(s); }
});
return root;
}
}
HomeViewModel.java
public class HomeViewModel extends ViewModel {
private MutableLiveData<String> mText;
public HomeViewModel() {
mText = new MutableLiveData<>();
mText.setValue("This is home fragment.");
}
public LiveData<String> getText() {
return mText;
}
}

More information about MutableLiveData here


Android
A navigation drawer menu
Making changes on the project

nav_header_main.xml

activity_main_drawer.xml

•Get more xml icons for your Drawer menu here, or here or here.
•Or create your own icons using your pictures with a size of 50 x 30
pixels.
•Or use the Image Asset Studio tool
Android
A navigation drawer menu
Making changes on the project

fragment_home.xml

Show the gallery of the device


public class GalleryFragment extends Fragment {
private GalleryViewModel galleryViewModel;
static final int REQUEST_GALLERY = 1;
public View onCreateView(@NonNull LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
View root=inflater.inflate(R.layout.fragment_gallery,container,false);

Intent intent = new Intent(Intent.ACTION_PICK,


android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent, REQUEST_GALLERY);

return root;
}
}
GalleryFragment.java

More info.- Show the gallery


Android
A navigation drawer menu
Making changes on the project

Send emails from your application

SendFragment.java
public class SendFragment extends Fragment {

private SendViewModel sendViewModel;

public View onCreateView(@NonNull LayoutInflater inflater,


ViewGroup container, Bundle savedInstanceState) {

View root = inflater.inflate(R.layout.fragment_send, container, false);

Intent emailIntent = new Intent(Intent.ACTION_SENDTO, Uri.fromParts("mailto","", null));


emailIntent.putExtra(Intent.EXTRA_SUBJECT, "Subject");
emailIntent.putExtra(Intent.EXTRA_TEXT, "Body");
startActivity(Intent.createChooser(emailIntent, "Send email..."));
return root;
}
}

More info:
Sharing text
Sending emails

Exercise: Do the same with the Sharing text option


Android
A navigation drawer menu
Adding new options to the project: WebView

Show the content of a website

Add a new fragment into mobile_navigation.xml


mobile_navigation.xml
<fragment
android:id="@+id/nav_web"
android:name="com.example.mynavigationdrawermenuwithas35.ui.web.WebFragment"
android:label="@string/menu_web"
tools:layout="@layout/fragment_web" />

Add a new fragment_web.xml layout with a WebView


fragment_web.xml
<WebView
android:id="@+id/webkit"
android:layout_width="match_parent"
android:layout_height="match_parent" />

Add the fragment to the mAppBarConfiguration array in MainActivity


MainActivity.java
mAppBarConfiguration = new AppBarConfiguration.Builder(
R.id. nav_home, R.id.nav_gallery, R.id.nav_slideshow,
R.id.nav_web, R.id.nav_share, R.id.nav_send)
.setDrawerLayout(drawer)
.build();
Android
A navigation drawer menu
Adding new options to the project: WebView

Add a web package and a WebFragment.java file

public class WebFragment extends Fragment {


WebView navegador;
public View onCreateView(@NonNull LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
View root = inflater.inflate(R.layout.fragment_web, container, false);
navegador = root.findViewById(R.id.webkit);
navegador.getSettings().setJavaScriptEnabled(true);
navegador.setWebViewClient(new WebViewClient());
navegador.loadUrl("http://www.7towns4europe.eu");
return root;
}
}

And do not forget …

<uses-permission android:name="android.permission.INTERNET" />


<application …..
<!– Other tags -->
</application>
AndroidManifest.xml
Android
A navigation drawer menu
Adding new options to the project: Camera

Follow the previous steps to add the camera menu option

Get the complete project here


Android
A navigation drawer menu

Exercise.- Create a new


project (My Adapters with
drawer menu), add the My
Adapters activities and
reorganize all of them using
a drawer menu.
Android

Annex: Tabbed activity


Android
Tabbed activity

Create a new Project using the Tabbed Activity template


Android
Tabbed activity
The Project

The Controller

The View
Android
Tabbed activity
The View
Android
Tabbed activity
The View

The Control
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// More code ...
}
Android
Tabbed activity
The Control
MainActivity.java
// Attributes
private SectionsPagerAdapter mSectionsPagerAdapter;
private ViewPager mViewPager;
// Methods
protected void onCreate(Bundle savedInstanceState) {
// Create the adapter that will return a fragment for each of the three primary sections of the activity.
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.container);
mViewPager.setAdapter(mSectionsPagerAdapter);
// More code ...
}
public static class PlaceholderFragment extends Fragment {
private static final String ARG_SECTION_NUMBER = "section_number";
public PlaceholderFragment() { }
public static PlaceholderFragment newInstance ( … ) { // Code }
@Override
public View onCreateView ( … ) { // More code … }
}
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) { …. }
@Override
public Fragment getItem(int position) { … }
@Override
public int getCount() { return 3; }
}
Android
Tabbed activity

Running the project

Swipe views provide lateral navigation between sibling screens such


as tabs with a horizontal finger gesture (a pattern sometimes known
as horizontal paging)

<resources>
<string name="app_name">El meu curs HTML</string>
<string name="action_settings">Settings</string>
<string name="home">Inici</string>
<string name="capitols">Capítols</string>
<string name="title_activity_capitols">Capítols del curs</string>
<string name="section_format"> Hello World from section: %1$d </string>
</resources>
}
strings.xml

More information about place holders here


Android
Tabbed activity layout 1.- An offline course
Create a new project using a Basic activity and a java class
Android
Tabbed activity layout 1.- An offline course
Add a new Tabbed activity

Add a new assets folder and a subfolder with your html pages

<!DOCTYPE html>
tema1.html
<html>
<head>
<meta charset='UTF-8'/>
<title> Un curs amb el mòbil.
HTML</title>
</head>
<body>
Tema 1.- Introducció a HTML
</body>
</html>
Android
Tabbed activity layout 1.- An offline course
Create the layout to show your web pages

fragment_capitols.xml
<WebView
android:id="@+id/capitol1_webview"
<!– More tags 🡪
/>
Android
Tabbed activity layout 1.- An offline course
Add the code to control the appearance of the web pages
CapitolsActivity.java
public static class PlaceholderFragment extends Fragment {
private static final String ARG_SECTION_NUMBER = "tema";
private static String newWebPage = null;

public PlaceholderFragment() { }
public static PlaceholderFragment newInstance(int sectionNumber) {
PlaceholderFragment fragment = new PlaceholderFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
fragment.setArguments(args);
return fragment;
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_capitols, container, false);
Integer numTopic = getArguments().getInt(ARG_SECTION_NUMBER);
newWebPage = ARG_SECTION_NUMBER + Integer.toString(numTopic) + ".html";
WebView myWebView = (WebView) rootView.findViewById(R.id.capitol1_webview);
myWebView.setWebViewClient(new WebViewClient());
myWebView.getSettings().setJavaScriptEnabled(true);
String strNumTopic = Integer.toString(numTopic);
String webPage = "file:///android_asset/capitols/" + newWebPage;
myWebView.loadUrl(webPage);
return rootView;
public Fragment getItem(int position) {
} return PlaceholderFragment.newInstance(position);
} } }
Android
Tabbed activity layout 1.- An offline course
Add the code to control the appearance of the web pages
CapitolsActivity.java
public class SectionsPagerAdapter extends FragmentPagerAdapter {

public SectionsPagerAdapter(FragmentManager fm) {


super(fm);
}

@Override
public Fragment getItem(int position) {
// getItem is called to instantiate the fragment for the given page.
// Return a PlaceholderFragment (defined as a static inner class below).
return PlaceholderFragment.newInstance(position + 1);
}

@Override
public int getCount() {
// Show total pages in the Capitol 1 folder
int fileCount = 0;
try { fileCount = getResources().getAssets().list("capitols").length;
} catch (IOException e) {
e.printStackTrace(); }
return fileCount;
}
}
Android
Tabbed activity layout 1.- An offline course

Running the project


???

What happens???
Exercise: Discover the problem and propose ways to solve it.

Take a look to the complete project here


Android
Tabbed activity layout 2.- Showing drawable pictures

Exercise: Show pictures using tabbed activity


Android
Tabbed activity layout 2.- Showing drawable pictures

Exercise: Show pictures using tabbed activity with submenus

}
}
Android
Tabbed activity layout 2.- Showing drawable pictures
Exercise: Show pictures using tabbed activity with submenus

1.- The menu view 1.- The menu control

menu_main.xml Mainmenu.java
<item @Override
android:id="@+id/home" public boolean onOptionsItemSelected(MenuItem item) {
android:orderInCategory="100" int id = item.getItemId();
android:title="@string/home" Bundle b = new Bundle();
app:showAsAction="never" /> if (id == R.id.home) {
<item Intent intent = new Intent (this, HomeActivity.class);
android:id="@+id/fotos" startActivity(intent);
android:title="@string/fotos" > }
<menu> if (id == R.id.android) {
}<item android:id="@+id/android"
android:title="@string/android" />
Intent intent = new Intent (this, MainActivity.class);
b.putString("foto", "android");
<item android:id="@+id/animal" intent.putExtras(b); //Adding the information to the intent
} android:title="@string/animal" /> startActivity(intent);
}
</menu>
</item> if (id == R.id.animal) {
Intent intent = new Intent (this, MainActivity.class);
b.putString("foto", "animal");
intent.putExtras(b); //Adding the information to the intent
startActivity(intent);
}
return super.onOptionsItemSelected(item);
}

Take a look to the complete project here


Android

Annex:
Other kind of menus
Android
User interfaces: Contextual menus

Contextual menus:
A contextual menu offers actions that affect a specific item or
context frame in the UI. You can provide a context menu for any
view.
Two ways to provide contextual actions:
In a floating context menu. A menu appears as a floating list
of menu items when the user performs a long-click on a view
that declares support for a context menu.
In the contextual action mode. Displays a contextual action
bar at the top of the screen with action items that affect the
selected item(s).
Android
User interfaces: Contextual menus

Creating a floating context menu. Steps:


1.- Create the context menu to be showed
2.- Register the View to which the context menu should be
associated by calling registerForContextMenu() and pass it the
View.
3.- Implement the onCreateContextMenu() method in your
Activity or Fragment.
4.- Implement onContextItemSelected().

1.- Create the context menu to be showed


<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:id="@+id/CtxLblOpc1"
android:title="@string/opcio1" />
<item
android:id="@+id/CtxLblOpc2"
android:title="@string/opcio2" />
</menu>
menu_contextual.xml
Android
User interfaces: Contextual menus
2.- Register the View to which the context menu should be associated
MainActivity.java
TextView lblText;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

lblText = (TextView) findViewById (R.id.txt_menu_contextual);


registerForContextMenu(lblText);
}
activity_main.xml
<!– More xml code 🡪
<TextView
android:id="@+id/txt_menu_contextual"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_marginLeft="40dp"
android:text="@string/menu_contextual" />
Android
User interfaces: Contextual menus
3.- Implement the onCreateContextMenu() method
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu_contextual, menu);
}
MainActivity.java
4.- Implement onContextItemSelected().
MainActivity.java
public boolean onContextItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.CtxLblOpc1:
lblText.setText("Option 1 clicked!"); return true;
case R.id.CtxLblOpc2:
lblText.setText("Option 2 clicked!!"); return true;
default:
return super.onContextItemSelected(item);
}
}

More info:
https://developer.android.com/reference/android/view/View.OnCreateContextMenuListener.html
Android
User interfaces: Contextual menus

Long click on the text

You might also like