Android 2 Android With Menus
Android 2 Android With Menus
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.
.
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);
//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>
<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);
}
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.
}
Android
A menu for selecting activities: The final result
Cut the onCreateOptionsMenu and onOptionsItemSelected from the
activities and add them into the MainMenu class.
@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
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;
}
}
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
es\strings.xml
<!-- Missatges personalitzats -->
<string name="start">Iniciando aplicación ...</string>
<string name="OK">Aceptar</string>
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
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" />
<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
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
return root;
}
}
GalleryFragment.java
SendFragment.java
public class SendFragment extends Fragment {
More info:
Sharing text
Sending emails
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
<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
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 {
@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
…
???
What happens???
Exercise: Discover the problem and propose ways to solve it.
}
}
Android
Tabbed activity layout 2.- Showing drawable pictures
Exercise: Show pictures using tabbed activity with submenus
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);
}
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
More info:
https://developer.android.com/reference/android/view/View.OnCreateContextMenuListener.html
Android
User interfaces: Contextual menus