Menus, Layout Managers and Event Listner
Menus, Layout Managers and Event Listner
Statement Purpose: Activity Outcomes:
Layouts
Event Listeners
Menus
Instructor Note:
Layout
A layout defines the visual structure for a user interface, such as the UI for an activity or app widget. Layout can be declared in two ways:
- Declare UI elements in XML
Android provides a straightforward XML vocabulary that corresponds to the View classes and subclasses, such as those for widgets and layouts.
- Instantiate layout elements at runtime
Our application can create View and ViewGroup objects (and manipulate their properties) programmatically. XML layout attributes named layout_something define layout parameters for the View that are appropriate for the ViewGroup in which it resides. Every ViewGroup class implements a nested class that extends ViewGroup.LayoutParams. This subclass contains property types that define the size and position for each child view, as appropriate for the view group. As given in the below picture, the parent view group defines layout parameters for each child view (including the child view group).
Android Layout Types There are number of Layouts provided by Android which you will use in almost all the Android applications to provide different view, look and feel.
Layout Attributes
Each layout has a set of attributes which define the visual properties of that layout. There are few common attributes among all the layouts and they are other attributes which are specific to that layout. Few attributes of layouts are given below.
View Group as layout
View Groups uper class represents containers of widgets/views
–Layout classes are also View Groups
–layouts are described in XML and mirror edin Java code
–Android provides several pre-existing layout managers; you can define your own custom layouts if needed
–layouts can be nested to achieve combinations of features
–widgets can be added to a view group, which will then manage that widget’s position/size behavior.
Menus
Menus are a common user interface component in many types of applications. To provide a familiar and consistent user experience, we should use the Menu APIs. There are three types of application menus:
Options Menu – The primary collection of menu items for an activity, which appears when the user touches the MENU button.
Context Menu – A floating list of menu items that appears when the user touches and holds a view that’s registered to provide a context menu.
Submenu – A floating list of menu items that appears when the user touches a menu item that contains a nested menu.
Although the design and user experience for some menu items have changed, the semantics to define a set of actions and options is still based on the Menu APIs. We will discuss how to create fundamental types of menus or action presentations on different versions of Android.
Options menu The options menu is the primary collection of menu items for an activity. It’s where we should place actions that have a global impact on the app, such as “Search,” “Compose email,” and “Settings.” If we are developing for Android 2.3 or lower, users can reveal the options menu panel by pressing the Menu button. On Android 3.0 and higher, items from the options menu are presented by the action bar as a combination of on-screen action items and overflow options. Beginning with Android 3.0, the Menu button is deprecated (some devices don’t have one), so we should migrate toward using the action bar to provide access to actions and other options.
The action bar is a window feature that identifies the user location, and provides user actions and navigation modes. Use of action bar in an app, offers the users a familiar
interface across applications that the system gracefully adapts for different screen configurations.
The action bar provides several key functions:
- Provides a dedicated space for giving our app an identity and indicating the user’s location in the
- Makes important actions prominent and accessible in a predictable way (such as
Search).
- Supports consistent navigation and view switching within apps (with tabs or drop- down lists).
Context menu
A context menu is a floating menu that appears when the user performs a long-click on an element. It provides actions that affect the selected content or context frame.
When developing for Android 3.0 and higher, we should instead use the contextual action mode to enable actions on selected content. This mode displays action items that affect the selected content in a bar at the top of the screen and allows the user to select multiple items.
Popup menu
A popup menu displays a list of items in a vertical list that’s anchored to the view that invoked the menu. It’s good for providing an overflow of actions that relate to specific content or to provide options for a second
part of a command. Actions in a popup menu should not directly affect the corresponding content— that’s what contextual actions are for. Rather, the popup menu is for extended actions that relate to regions of content in our activity.
The easiest way to create a menu is to define the menu in XML layout and then inflate a menu resource during the onCreateOptionsMenu() callback method.
When the user selects a menu item from the Options Menu the system calls the activity’s onOptionsItemSelected() method.This method passes the MenuItem that the user selected. We can identify the menu item by calling getItemId(), which returns the unique ID for the menu item (defined by the android:id attribute in the menu resource or with an integer given to the add() method). We can match this ID against known menu items and perform the appropriate action. A menu group is a collection of menu items that share certain traits. With a group, you can:
Show or hide all items with setGroupVisible()
Enable or disable all items with setGroupEnabled()
Specify whether all items are checkable with setGroupCheckable()
Dynamically Changing menu items at runtime
Once the activity is created, the onCreateOptionsMenu() method is called only once, as described above. The system keeps and re-uses the Menu defined in this method until the activity is destroyed. If we want to change the Options Menu any time after it’s first created, we must override the onPrepareOptionsMenu() method. This passes the Menu object as it currently exists.
This example only deals with Options menu and Submenu only. This sample code helps to understand the Menu life cycle and how to create menus using XML layout and programmatically using code for adding and removing menus dynamically.
Introduction
We create native calculator application in android. This application will perform mathematical operation into the android device. Let us design for UI in activity_main.xml
Activities:
ACTIVITY: Step 1: Design for UI in layout file (activity_main.xml)
Activity_main.xml
<LinearLayout xmlns:android
xmlns:tools=”http://schemas.android.com/tools” android:layout_width=”match_parent” android:layout_height=”match_parent” android:orientation=”vertical” android:paddingBottom=”@dimen/activity_vertical_margin” android:paddingLeft=”@dimen/activity_horizontal_margin” android:paddingRight=”@dimen/activity_horizontal_margin” android:paddingTop=”@dimen/activity_vertical_margin” tools:context=”.Home” android:background=”#fff” android:weightSum=”1″>
<LinearLayout
android:orientation=”horizontal” android:layout_width=”match_parent” android:layout_height=”72dp” android:id=”@+id/onoff”>
<Switch android:layout_width=”match_parent” android:layout_height=”match_parent” android:id=”@+id/switch1″ android:checked=”false” />
</LinearLayout>
<LinearLayout
android:orientation=”horizontal” android:layout_width=”match_parent” android:layout_height=”55dp” android:layout_gravity=”center_horizontal” android:id=”@+id/l1″> cseitquestions.blogspot.in cseitquestions.blogspot.in
<EditText android:layout_width=”wrap_content” android:layout_height=”wrap_content” android:id = “@+id/display” android:hint=”Enter the Values” android:layout_weight=”1″ />
</LinearLayout>
<LinearLayout
android:orientation=”horizontal” android:layout_width=”fill_parent” android:layout_height=”wrap_content” android:gravity=”center” android:paddingTop=”20dp” android:id=”@+id/l5″>
<Button android:layout_width=”55dp” android:layout_height=”wrap_content” android:id = “@+id/one” android:text=”1″ />
<Button android:layout_width=”55dp” android:layout_height=”wrap_content” android:id = “@+id/two” android:text=”2″ />
<Button android:layout_width=”55dp” android:layout_height=”wrap_content” android:id = “@+id/three” android:text=”3″ />
<Button android:layout_width=”55dp” android:layout_height=”wrap_content” android:id = “@+id/div” android:text=”/” />
</LinearLayout> cseitquestions.blogspot.in cseitquestions.blogspot.in
<LinearLayout android:orientation=”horizontal” android:layout_width=”fill_parent” android:layout_height=”wrap_content” android:layout_gravity=”center” android:gravity=”center” android:paddingTop=”20dp” android:id=”@+id/l2″> <Button android:layout_width=”55dp” android:layout_height=”wrap_content” android:id = “@+id/four” android:text=”4″ /> <Button android:layout_width=”55dp” android:layout_height=”wrap_content” android:id = “@+id/five” android:text=”5″ />
<Button android:layout_width=”55dp” android:layout_height=”wrap_content” android:id = “@+id/six” android:text=”6″ /> <Button android:layout_width=”55dp” android:layout_height=”wrap_content” android:id = “@+id/mul” android:text=”*” />
</LinearLayout> <LinearLayout
android:orientation=”horizontal” android:layout_width=”fill_parent” android:layout_height=”wrap_content” android:gravity=”center” android:paddingTop=”20dp” android:id=”@+id/l3″> cseitquestions.blogspot.in cseitquestions.blogspot.in
<Button android:layout_width=”55dp” android:layout_height=”wrap_content” android:id = “@+id/seven” android:text=”7″ /> <Button android:layout_width=”55dp” android:layout_height=”wrap_content” android:id = “@+id/eight” android:text=”8″ />
<Button android:layout_width=”55dp” android:layout_height=”wrap_content” android:id = “@+id/nine” android:text=”9″ /> <Button android:layout_width=”55dp” android:layout_height=”wrap_content” android:id = “@+id/sub” android:text=”-” />
</LinearLayout> <LinearLayout android:orientation=”horizontal”
android:layout_width=”fill_parent” android:layout_height=”wrap_content” android:gravity=”center” android:paddingTop=”20dp” android:id=”@+id/l4″> <Button android:layout_width=”55dp” android:layout_height=”wrap_content” android:id = “@+id/cancel” android:text=”C” /> <Button android:layout_width=”55dp” android:layout_height=”wrap_content” android:id = “@+id/zero” android:text=”0″ />
<Button android:layout_width=”55dp”
android:layout_height=”wrap_content” android:id = “@+id/equal” android:text=”=” /> cseitquestions.blogspot.in cseitquestions.blogspot.in
<Button android:layout_width=”55dp” android:layout_height=”wrap_content” android:id = “@+id/add” android:text=”+” /> </LinearLayout> </LinearLayout> Step 2: Open MainActivity.java and add following code package com.example.kamarajios33.calc; import android.os.Bundle; import android.app.Activity; import android.support.annotation.RequiresPermission; import android.text.Editable; import android.view.Menu; import android.view.View; import android.widget.Button; import android.widget.CompoundButton; import android.widget.EditText; import android.widget.Switch; public class MainActivity extends Activity implements View.OnClickListener { Button one, two, three, four, five, six, seven, eight, nine, zero, add, sub, mul, div, cancel, equal; EditText disp; int op1; int op2; String optr; Switch onoff; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); onoff = (Switch)findViewById(R.id.switch1); onoff.setChecked(true);
one = (Button) findViewById(R.id.one); two = (Button) findViewById(R.id.two); cseitquestions.blogspot.in cseitquestions.blogspot.in
three = (Button) findViewById(R.id.three); four = (Button) findViewById(R.id.four); five = (Button) findViewById(R.id.five); six = (Button) findViewById(R.id.six); seven = (Button) findViewById(R.id.seven); eight = (Button) findViewById(R.id.eight); nine = (Button) findViewById(R.id.nine); zero = (Button) findViewById(R.id.zero); add = (Button) findViewById(R.id.add); sub = (Button) findViewById(R.id.sub); mul = (Button) findViewById(R.id.mul); div = (Button) findViewById(R.id.div);
cancel = (Button) findViewById(R.id.cancel); equal = (Button) findViewById(R.id.equal); disp
= (EditText) findViewById(R.id.display); onoff.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { if(isChecked)
{ one.setEnabled(true); two.setEnabled(true); three.setEnabled(true); four.setEnabled(true); five.setEnabled(true); six.setEnabled(true); seven.setEnabled(true); eight.setEnabled(true);
nine.setEnabled(true); zero.setEnabled(true); add.setEnabled(true); sub.setEnabled(true); mul.setEnabled(true);
sub.setEnabled(true); cseitquestions.blogspot.in cseitquestions.blogspot.in mul.setEnabled(true); div.setEnabled(true); cancel.setEnabled(true); equal.setEnabled(true); disp.setEnabled(true); } else { one.setEnabled(false); two.setEnabled(false); three.setEnabled(false); four.setEnabled(false); five.setEnabled(false); six.setEnabled(false); seven.setEnabled(false); eight.setEnabled(false); nine.setEnabled(false); zero.setEnabled(false); add.setEnabled(false); sub.setEnabled(false); mul.setEnabled(false); sub.setEnabled(false); mul.setEnabled(false); div.setEnabled(false); cancel.setEnabled(false); equal.setEnabled(false); disp.setEnabled(false); } } }); try { one.setOnClickListener(this); two.setOnClickListener(this); three.setOnClickListener(this); four.setOnClickListener(this); five.setOnClickListener(this); cseitquestions.blogspot.in cseitquestions.blogspot.in six.setOnClickListener(this);
seven.setOnClickListener(this); eight.setOnClickListener(this); nine.setOnClickListener(this); zero.setOnClickListener(this); cancel.setOnClickListener(this); add.setOnClickListener(this); sub.setOnClickListener(this); mul.setOnClickListener(this); div.setOnClickListener(this); equal.setOnClickListener(this); } catch (Exception e) {
} }
public void operation() { if (optr.equals(“+”)) {
op2 = Integer.parseInt(disp.getText().toString()); disp.setText(“”); op1 = op1 + op2; disp.setText(Integer.toString(op1));
} else if (optr.equals(“-“)) {
op2 = Integer.parseInt(disp.getText().toString()); disp.setText(“”); op1 = op1 – op2; disp.setText(Integer.toString(op1));
} else if (optr.equals(“*”)) {
op2 = Integer.parseInt(disp.getText().toString()); disp.setText(“”); op1 = op1 * op2; disp.setText(Integer.toString(op1));
} else if (optr.equals(“/”)) {
op2 = Integer.parseInt(disp.getText().toString()); disp.setText(“”); op1 = op1 / op2; disp.setText(Integer.toString(op1));
} } cseitquestions.blogspot.in cseitquestions.blogspot.in @Override
public void onClick(View arg0)
{
Editable str = disp.getText(); switch (arg0.getId()) { case R.id.one:
if (op2 != 0) { op2 = 0; disp.setText(“”);
}
str = str.append(two.getText()); disp.setText(str); break;
case R.id.two: if (op2 != 0) { op2 = 0; disp.setText(“”);
}
str = str.append(two.getText()); disp.setText(str); break;
case R.id.three: if (op2 != 0) { op2 = 0; disp.setText(“”);
}
str = str.append(three.getText()); disp.setText(str); break;
case R.id.four: if (op2 != 0) { op2 = 0; disp.setText(“”);
}
str = str.append(four.getText()); disp.setText(str);
break; cseitquestions.blogspot.in cseitquestions.blogspot.in case R.id.five: if (op2 != 0) {
op2 = 0; disp.setText(“”);
}
str = str.append(five.getText()); disp.setText(str); break; case R.id.six:
if (op2 != 0) { op2 = 0; disp.setText(“”);
}
str = str.append(six.getText()); disp.setText(str); break;
case R.id.seven: if (op2 != 0) { op2 = 0; disp.setText(“”);
}
str = str.append(seven.getText()); disp.setText(str); break;
case R.id.eight: if (op2 != 0) { op2 = 0; disp.setText(“”);
}
str = str.append(eight.getText()); disp.setText(str);
break; cseitquestions.blogspot.in cseitquestions.blogspot.in
case R.id.nine: if (op2 != 0) { op2 = 0; disp.setText(“”); } str = str.append(nine.getText()); disp.setText(str); break; case R.id.zero: if (op2 != 0) { op2 = 0; disp.setText(“”); } str = str.append(zero.getText()); disp.setText(str); case R.id.cancel: op1 = 0; op2 = 0; disp.setText(“”); disp.setHint(“Perform Operation”); break; case R.id.add: optr = “+”; if (op1
== 0) { op1 = Integer.parseInt(disp.getText().toString()); disp.setText(“”); } else if (op2 != 0) { op2 = 0; disp.setText(“”); } else { op2 = Integer.parseInt(disp.getText().toString()); disp.setText(“”); op1 = op1 + op2; disp.setText(Integer.toString(op1)); }
break; cseitquestions.blogspot.in cseitquestions.blogspot.in
case R.id.sub: optr = “-“; if (op1 == 0) { op1 = Integer.parseInt(disp.getText().toString()); disp.setText(“”); } else if (op2 != 0) { op2 = 0; disp.setText(“”); } else { op2 = Integer.parseInt(disp.getText().toString()); disp.setText(“”); op1 = op1 – op2; disp.setText(Integer.toString(op1)); } break; case R.id.mul: optr = “*”; if (op1 == 0) { op1 = Integer.parseInt(disp.getText().toString()); disp.setText(“”); } else if (op2 != 0) { op2 = 0; disp.setText(“”); } else { op2 = Integer.parseInt(disp.getText().toString()); disp.setText(“”); op1 = op1 * op2; disp.setText(Integer.toString(op1)); }
break; cseitquestions.blogspot.in cseitquestions.blogspot.in case R.id.div: optr = “/”;
if (op1 == 0)
{
op1 = Integer.parseInt(disp.getText().toString()); disp.setText(“”);
}
else if (op2 != 0) { op2 = 0; disp.setText(“”);
}
else
{
op2 = Integer.parseInt(disp.getText().toString()); disp.setText(“”); op1 = op1 / op2; disp.setText(Integer.toString(op1));
}
break;
case R.id.equal:
if (!optr.equals(null))
{
if (op2 != 0)
{
if (optr.equals(“+”))
{
disp.setText(“”); op1 = op1 + op2; disp.setText(Integer.toString(op1));
}
else if (optr.equals(“-“))
{
disp.setText(“”); op1 = op1 – op2;
disp.setText(Integer.toString(op1));
} cseitquestions.blogspot.in cseitquestions.blogspot.in else if (optr.equals(“*”))
{
disp.setText(“”); op1 = op1 * op2; disp.setText(Integer.toString(op1));
}
else if (optr.equals(“/”))
{
disp.setText(“”); op1 = op1 / op2; disp.setText(Integer.toString(op1));
}
}
else
{
operation();
}
}break; }
}}
ACTIVITY: Running the Layout Managers and Event Click Listener App
Step 1: Create an android project using android studio
Step 2: After creating the project, open the res directory -> layout -> resource file namedactivity_main.xml
Step 3: Create two resource (*.xml) file named activity_second.xml, activity_third.xml & twoactivity (*.java) file named second.java and third.java file.
Right click res directory -> New -> Activity -> Empty Activity
Step 5: Create new Resource directory named menu and new resource file named menu
Right click res directory -> New -> Android Resource Directory -> resource type -> select menu -> finish.
Right click menu directory -> New -> new menu resource file -> enter file name -> Ok
Step 4: Design (After the design, the xml code will be generated automatically in the layout file )
Open menu.xml and add the following code
<?xml version=”1.0″ encoding=”utf-8″?>
<menu xmlns:android=”http://schemas.android.com/apk/res/android” xmlns:tools=”http://schemas.android.com/tools” tools:context=”com.example.kamarajios33.menu.MainActivity”><item android:id=”@+id/one”
android:title=”One”/>
<item
android:id=”@+id/two” android:title=”Two”/>
</menu>
Step 6: Open MainActivity.java, second.java & third.java and add the following code
MainActivity.java
public class MainActivity extends AppCompatActivity { Button b1; @Override
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); b1=(Button)findViewById(R.id.b1); b1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
PopupMenu pm = new PopupMenu(MainActivity.this,b1); pm.getMenuInflater().inflate(R.menu.menu,pm.getMenu()); pm.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() { @Override
public boolean onMenuItemClick(MenuItem item)
{ switch (item.getItemId()) { case R.id.one:
Intent o = new Intent(getApplicationContext(), second.class); startActivity(o); System.exit(0);
case R.id.two: Intent in = new Intent(getApplicationContext(),third.class); startActivity(in); System.exit(0); break; } return false; } }); pm.show(); } }); } }
The output of the above code is as follows.
Home Activities:
- Write XML code for generating the following layout.