Documente Academic
Documente Profesional
Documente Cultură
Android Option Menus are the primary menus of android. They can be used for
settings, search, delete item etc.
Here, we are going to see two examples of option menus. First, the simple option menus
and second, options menus with images.
Here, we are inflating the menu by calling the inflate() method of MenuInflater class.
To perform event handling on menu items, you need to
override onOptionsItemSelected() method of Activity class.
activity_main.xml
File: activity_main.xml
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="@style/AppTheme.AppBarOverlay">
<android.support.v7.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:popupTheme="@style/AppTheme.PopupOverlay" />
</android.support.design.widget.AppBarLayout>
<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>
menu_main.xml
File: menu_main.xml
<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="example.javatpoint.com.optionmenu.MainActivity">
<item android:id="@+id/item1"
android:title="Item 1"/>
<item android:id="@+id/item2"
android:title="Item 2"/>
<item android:id="@+id/item3"
android:title="Item 3"
app:showAsAction="withText"/>
</menu>
Activity class
This class displays the content of menu.xml file and performs event handling on clicking
the menu items.
File: MainActivity.java
package example.javatpoint.com.optionmenu;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
switch (id){
case R.id.item1:
Toast.makeText(getApplicationContext(),"Item 1 Selected",Toast.LENGTH_LONG)
.show();
return true;
case R.id.item2:
Toast.makeText(getApplicationContext(),"Item 2 Selected",Toast.LENGTH_LONG)
.show();
return true;
case R.id.item3:
Toast.makeText(getApplicationContext(),"Item 3 Selected",Toast.LENGTH_LONG)
.show();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}
activity_main.xml
Drag one listview from the pallete, now the xml file will look like this:
File: activity_main.xml
<ListView
android:layout_width="368dp"
android:layout_height="495dp"
android:id="@+id/listView"
android:layout_marginEnd="8dp"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</android.support.constraint.ConstraintLayout>
main_menu.xml
Activity class
Let's write the code to display the context menu on press of the listview.
File: MainActivity.java
package example.javatpoint.com.contextmenu;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
Output:
activity_main.xml
File: activity_main.xml
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/button"
android:text="Click"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</android.support.constraint.ConstraintLayout>
popup_menu.xml
It contains three items as show below. It is created inside the res/menu directory.
File: poupup_menu.xml
Activity class
File: MainActivity.java
package example.javatpoint.com.popupmenu;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.PopupMenu;
import android.widget.Toast;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
@Override
public void onClick(View v) {
//Creating the instance of PopupMenu
PopupMenu popup = new PopupMenu(MainActivity.this, button);
//Inflating the Popup using xml file
popup.getMenuInflater().inflate(R.menu.popup_menu, popup.getMenu());
Output:
ArrayAdapter
In android, An adapter is a bridge between UI component and data source that helps
us to fill data in UI component. It holds the data and send the data to adapterview
then view can takes the data from the adapter view and shows the data on different
views like listview, gridview, spinner etc. ArrayAdapter is more simple and commonly
used Adapter in android.
Whenever you have a list of single type of items which is backed by an array,
you can use ArrayAdapter. For instance, list of phone contacts, countries or
names.
By default, ArrayAdapter expects a Layout with a single TextView, If you want
to use more complex views means more customization in grid items or list
items, please avoid ArrayAdapter and use custom adapters.
context:
The first parameter is used to pass the context means the reference of current class.
Here this is a keyword used to show the current class reference. We can also use
getApplicationContext(), getActivity() in the place of this keyword.
getApplicationContext() is used in a Activity and getActivity() is used in a Fragment.
Below is the example code in which we set the current class reference in a adapter.
resource:
The second parameter is resource id used to set the layout(xml file) for list items in
which you have a text view.
Below is the example code in which we set the layout.
ArrayAdapter arrayAdapter = new ArrayAdapter(this, R.layout.list_view_items, int t
extViewResourceId, T[] objects);
textViewResourceId:
objects:
The fourth parameter is an array of objects, used to set the array of elements in
the textView. We can set the object of array or array list here.
Below is the example code in which we set the Animal array in adapter to display the
Animal name’s list.
Example of an ArrayAdapter:
Example 1: Below is the example, in which we displays a list of animal names in a list
view using simple array adapter. Below is the final output and code:
Step 2: Now open app -> res -> layout -> xml (or) activity_main.xml and add following
code :
<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"
tools:context=".MainActivity">
<ListView
android:id="@+id/simpleListView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:divider="#000"
android:dividerHeight="2dp"/>
</RelativeLayout>
Step 3: Create a new Activity activity_list_view.xml and add the below code
<TextView
android:id="@+id/textView"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:padding="@dimen/activity_horizontal_margin"
android:textColor="#000" />
</LinearLayout>
Step 4: Now Open app -> java -> package -> MainActivity.java and add the below code.
Here we will use ArrayAdapter to display the items in Listview.
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.ListView;
}
}
Output:
Now run the App in Emulator and you will see the below output:
Example 2: Below is the example, In which we display a list of Animal’s name
in spinner using ArrayAadapter. Below is the final output and code:
Step 2: Now open app -> res -> layout -> activity_main.xml (or) main.xml and add
following code:
<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"
tools:context=".MainActivity">
<Spinner
android:id="@+id/animalNamesSpinner"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"/>
</RelativeLayout>
Step 3: Now create a new Activity simple_spinner_item.xml and add the below code:
Step 4: Now open app -> java -> package -> MainActivity.java and add the following
code
package example.abhiandriod.arrayadapterexample;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.Toast;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Getting the instance of Spinner and applying OnItemSelectedListener on i
t
Spinner spin = (Spinner) findViewById(R.id.animalNamesSpinner);
spin.setOnItemSelectedListener(this);
@Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
}
Output:
Now run the App in Emulator you will see the animals name listed in a Spinner
BaseAdapter In Android Studio
Before we share BaseAdapter it is first important to revise Adapter. In android,
an adapter is a bridge between UI component and data source that helps us to fill data
in the UI component. It holds the data and send the data to adapter view then view
can takes the data from the adapter view and shows the data on different views like
as list view, grid view, spinner etc. For more customization of views we uses the base
adapter. Now lets discuss BaseAdapter class.
@Override
public int getCount() {
return 0;
}
@Override
public Object getItem(int i) {
return null;
}
@Override
public long getItemId(int i) {
return 0;
}
@Override
public View getView(int i, View view, ViewGroup viewGroup) {
return null;
}
In the above code snippet we see the overrided methods of BaseAdapter which are
used to set the data in a list, grid or a spinner. From there we mainly used two
functions getCount() and getView().
Let’s discuss all these functions in detail:
1. getCount():
The getCount() function returns the total number of items to be displayed in a list. It
counts the value from array list size() method or an array’s length. For example, if we
have an list of elements in an arraylist and we have to display the items in a list
view then we can count the total number of elements using the size function and then
that integer value is returned by the function getCount() as shown below.
@Override
public int getCount() {
int count=arrayList.size(); //counts the total number of elements from the arrayLi
st
return count;//returns the total count to adapter
}
3. getItem(int i):
This function is used to Get the data item associated with the specified position in the
data set to obtain the corresponding data of the specific location in the collection of
data items.
Below is the example code in which we returns the array list’s item according to
position.
@Override
public Object getItem(int i) {
return arrayList.get(i);
}
4. getItemId(int i):
As for the getItemId (int position), it returns the corresponding to the position item ID.
The function returns a long value of item position to the adapter.
Below is the code in which we returns the position.
@Override
public long getItemId(int i) {
return i;
}
<GridView
android:id="@+id/simpleGridView"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:footerDividersEnabled="false"
android:numColumns="3" />
</LinearLayout>
Step 3: Create a new Activity activity_gridview.xml inside layout and add the below
code:
Step 3: Now open app -> java -> package -> MainActivity.java and add the below code.
Make sure you have images saved in drawable folder with the names we have used or
else change the name based on the images present in your drawable folder.
package example.abhiandriod.baseadapterexample;
import android.app.Activity;
import android.os.Bundle;
import android.widget.GridView;
GridView simpleGrid;
int animals[] = {R.drawable.animal13, R.drawable.animal14, R.drawable.animal15, R.
drawable.animal16, R.drawable.animal17, R.drawable.animal18, R.drawable.animal15,
R.drawable.animal16, R.drawable.animal17};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
simpleGrid = (GridView) findViewById(R.id.simpleGridView);
CustomAdapter customAdapter = new CustomAdapter(getApplicationContext(), animals);
simpleGrid.setAdapter(customAdapter);
}
}
Step 4: Create a new class CustomAdapter.java inside package and add the following
code
package example.abhiandriod.baseadapterexample; //Use your package
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
@Override
public int getCount() {
return animals.length;
}
@Override
public Object getItem(int i) {
return null;
}
@Override
public long getItemId(int i) {
return 0;
}
@Override
public View getView(int i, View view, ViewGroup viewGroup) {
view = inflter.inflate(R.layout.activity_gridview, null);
ImageView icon = (ImageView) view.findViewById(R.id.icon);
icon.setImageResource(animals[i]);
return view;
}
}
Output:
Now run the App in Emulator you will see Animals listed in Grids. So this is one use of
BaseAdapter in Gridview.