Android
Android
com/android-hide-title-bar-example
You need to follow the 3 steps mentioned above for creating the Hello android application.
2) Provide the following information: Application name, Company domain, Project location and Package
name of application and click next.
1
3) Select the API level of application and click next.
2
5) Provide the Activity Name and click finish.
3
After finishing the Activity configuration, Android Studio auto generates the activity class and
other required configuration files.
Now an android project has been created. You can explore the android project and see the simple
program, it looks like this:
4
2) Write the message
File: activity_main.xml
Android studio auto generates code for activity_main.xml file. You may edit this file according
to your requirement.
File: MainActivity.java
1. package first.javatpoint.com.welcome;
2.
3. import android.support.v7.app.AppCompatActivity;
4. import android.os.Bundle;
5.
6. public class MainActivity extends AppCompatActivity {
7. @Override
8. protected void onCreate(Bundle savedInstanceState) {
9. super.onCreate(savedInstanceState);
10. setContentView(R.layout.activity_main);
11. }
12. }
To run the android application, click the run icon on the toolbar or simply press Shift + F10.
The android emulator might take 2 or 3 minutes to boot. So please have patience. After booting the
emulator, the android studio installs the application and launches the activity. You will see something like
this:
6
The android emulator might take 2 or 3 minutes to boot. So please have patience. After booting the
emulator, the android studio installs the application and launches the activity. You will see something like
this:
Hello Android
Android application contains different components such as java source code, string resources,
images, manifest file, apk file etc. Let's understand the project structure of android application.
7
Java Source Code
Let's see the java source file created by the Eclipse IDE:
File: MainActivity.java
1. package com.example.helloandroid;
2. import android.os.Bundle;
3. import android.app.Activity;
4. import android.view.Menu;
5. import android.widget.TextView;
6. public class MainActivity extends Activity {//(1)
8
7. @Override
8. protected void onCreate(Bundle savedInstanceState) {//(2)
9. super.onCreate(savedInstanceState);
10.
11. setContentView(R.layout.activity_main);//(3)
12. }
13. @Override
14. public boolean onCreateOptionsMenu(Menu menu) {//(4)
15. // Inflate the menu; this adds items to the action bar if it is present.
16. getMenuInflater().inflate(R.menu.activity_main, menu);
17. return true;
18. }
19. }
(1) Activity is a java class that creates and default window on the screen where we can place
different components such as Button, EditText, TextView, Spinner etc. It is like the Frame of
Java AWT.
It provides life cycle methods for activity such as onCreate, onStop, OnResume etc.
(2) The onCreate method is called when Activity class is first created.
File: activity_main.xml
<RelativeLayout xmlns:androclass="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" >
9
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:text="@string/hello_world" />
</RelativeLayout>
As you can see, a textview is created by the framework automatically. But the message for
this string is defined in the strings.xml file. The @string/hello_world provides information
about the textview message. The value of the attribute hello_world is defined in the
strings.xml file.
File: strings.xml
<resources>
<string name="app_name">helloandroid</string>
<string name="menu_settings">Settings</string>
</resources>
You can change the value of the hello_world attribute from this file.
It is the auto-generated file that contains IDs for all the resources of res directory. It is generated
by aapt(Android Asset Packaging Tool). Whenever you create any component on activity_main,
a corresponding ID is created in the R.java file which can be used in the Java Source file later.
File: R.java
*/
package com.example.helloandroid;
11
}
/**
Base application theme for API 11+. This theme completely replaces
Base application theme for API 14+. This theme completely replaces
*/
All customizations that are NOT specific to a particular API-level can go here.
*/
12
APK File
An apk file is created by the framework automatically. If you want to run the android application
on the mobile, transfer and install it.
Resources
Manifest file
It contains information about package including components such as activities, services, content
providers etc.
For more information about manifest file visit here: AndroidManifest.xml file.
The Dalvik Virtual Machine (DVM) is an android virtual machine optimized for mobile
devices. It optimizes the virtual machine for memory, battery life and performance.
Dalvik is a name of a town in Iceland. The Dalvik VM was written by Dan Bornstein.
The Dex compiler converts the class files into the .dex file that run on the Dalvik VM. Multiple
class files are converted into one dex file.
Let's see the compiling and packaging process from the source file:
13
The javac tool compiles the java source file into the class file.
The dx tool takes all the class files of your application and generates a single .dex file. It is a
platform-specific tool.
The Android Assets Packaging Tool (aapt) handles the packaging process.
This is the required xml file for all the android application and located inside the root directory.
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
14
package="com.javatpoint.hello"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="15" />
<application
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="@string/title_activity_main" >
<intent-filter>
</intent-filter>
</activity>
</application>
15
</manifest>
The elements used in the above xml file are described below.
<manifest>
manifest is the root element of the AndroidManifest.xml file. It has package attribute that
describes the package name of the activity class.
<application>
application is the subelement of the manifest. It includes the namespace declaration. This
element contains several subelements that declares the application component such as activity
etc.
The commonly used attributes are of this element are icon, label, theme etc.
android:icon represents the icon for all the android application components.
android:label works as the default label for all the application components.
<activity>
activity is the subelement of application and represents an activity that must be defined in the
AndroidManifest.xml file. It has many attributes such as label, name, theme, launchMode etc.
<intent-filter>
intent-filter is the sub-element of activity that describes the type of intent to which activity,
service or broadcast receiver can respond to.
<action>
It adds an action for the intent-filter. The intent-filter must have at least one action element.
16
<category>
If you create any component in the activity_main.xml file, id for the corresponding component is
automatically created in this file. This id can be used in the activity source file to perform any
action on the component.
Let's see the android R.java file. It includes a lot of static nested classes such as menu, id, layout,
attr, drawable, string etc.
*/
package com.example.helloandroid;
}
17
public static final class id {
/**
18
Base application theme for API 11+. This theme completely replaces
Base application theme for API 14+. This theme completely replaces
*/
All customizations that are NOT specific to a particular API-level can go here.
*/
19
In this example, we are going to explain how to hide the title bar and how to display content in
full screen mode.
The getSupportActionBar() method is used to retrieve the instance of ActionBar class. Calling
the hide() method of ActionBar class hides the title bar.
The setFlags() method of Window class is used to display content in full screen mode. You need
to pass the WindowManager.LayoutParams.FLAG_FULLSCREEN constant in the setFlags
method.
this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
Let's see the full code to hide the title bar in android.
activity_main.xml
File: activity_main.xml
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/a
pk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
20
android:layout_height="match_parent"
tools:context="first.javatpoint.com.hidetitlebar.MainActivity">
<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>
Activity class
File: MainActivity.java
package first.javatpoint.com.hidetitlebar;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Window;
import android.view.WindowManager;
21
@Override
super.onCreate(savedInstanceState);
this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
setContentView(R.layout.activity_main);
Syntax:
<activity android:name="package_name.Your_ActivityName"
android:screenOrientation="orirntation_type">
</activity>
Example:
android:screenOrientation="portrait">
22
</activity>
<activity android:name=".SecondActivity"
android:screenOrientation="landscape">
</activity>
Value Description
unspecified It is the default value. In such case, system chooses the orientation.
Portrait taller not wider
landscape wider not taller
sensor orientation is determined by the device orientation sensor.
In this example, we will create two activities of different screen orientation. The first activity
(MainActivity) will be as "portrait" orientation and second activity (SecondActivity) as
"landscape" orientation type.
activity_main.xml
File: activity_main.xml
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/a
pk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="example.javatpoint.com.screenorientation.MainActivity">
23
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp"
android:layout_marginTop="112dp"
android:onClick="onClick"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.612"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/editText1"
app:layout_constraintVertical_bias="0.613" />
<TextView
android:id="@+id/editText1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_marginEnd="8dp"
android:layout_marginStart="8dp"
android:layout_marginTop="124dp"
24
android:ems="10"
android:textSize="22dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.502"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</android.support.constraint.ConstraintLayout>
Activity class
File: MainActivity.java
package example.javatpoint.com.screenorientation;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
Button button1;
@Override
25
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button1=(Button)findViewById(R.id.button1);
startActivity(intent);
activity_second.xml
File: activity_second.xml
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/a
pk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="example.javatpoint.com.screenorientation.SecondActivity">
<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
26
android:layout_height="wrap_content"
android:layout_marginEnd="8dp"
android:layout_marginStart="8dp"
android:layout_marginTop="180dp"
android:textSize="22dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.502"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</android.support.constraint.ConstraintLayout>
SecondActivity class
File: SecondActivity.java
package example.javatpoint.com.screenorientation;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
@Override
super.onCreate(savedInstanceState);
27
setContentView(R.layout.activity_second);
AndroidManifest.xml
File: AndroidManifest.xml
In AndroidManifest.xml file add the screenOrientation attribute in activity and provides its
orientation. In this example, we provide "portrait" orientation for MainActivity and "landscape"
for SecondActivity.
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="example.javatpoint.com.screenorientation">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity
android:name="example.javatpoint.com.screenorientation.MainActivity"
android:screenOrientation="portrait">
<intent-filter>
28
<action android:name="android.intent.action.MAIN" />
</intent-filter>
</activity>
<activity android:name=".SecondActivity"
android:screenOrientation="landscape">
</activity>
</application>
</manifest>
Android Widgets
There are given a lot of android widgets with simplified examples such as Button, EditText,
AutoCompleteTextView, ToggleButton, DatePicker, TimePicker, ProgressBar etc.
Android widgets are easy to learn. The widely used android widgets with examples are given
below:
Android Button
Android Toast
Custom Toast
We are able to customize the toast, such as we can display image on the toast
ToggleButton
AlertDialog
AlertDialog displays a alert dialog containing the message with OK and Cancel buttons.
Spinner
Spinner displays the multiple options, but only one can be selected at a time.
AutoCompleteTextView
RatingBar
DatePicker
Datepicker displays the datepicker dialog that can be used to pick the date.
TimePicker
TimePicker displays the timepicker dialog that can be used to pick the time.
ProgressBar
30
Android Button Example with Listener
Here, we are going to create two textfields and one button for sum of two numbers. If user clicks
button, sum of two input values is displayed on the Toast.
We can perform action on button using different types such as calling listener on button or
adding onClick property of button in activity's xml file.
button.setOnClickListener(new View.OnClickListener() {
@Override
//code
});
<Button
android:onClick="methodName"
/>
First of all, drag 2 textfields from the Text Fields palette and one button from the Form Widgets
palette as shown in the following figure.
31
The generated code for the ui components will be like this:
File: activity_main.xml
<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:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="example.javatpoint.com.sumoftwonumber.MainActivity">
32
<EditText
android:id="@+id/editText1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="61dp"
android:ems="10"
android:inputType="number"
tools:layout_editor_absoluteX="84dp"
tools:layout_editor_absoluteY="53dp" />
<EditText
android:id="@+id/editText2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/editText1"
android:layout_centerHorizontal="true"
android:layout_marginTop="32dp"
android:ems="10"
android:inputType="number"
tools:layout_editor_absoluteX="84dp"
33
tools:layout_editor_absoluteY="127dp" />
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/editText2"
android:layout_centerHorizontal="true"
android:layout_marginTop="109dp"
android:text="ADD"
tools:layout_editor_absoluteX="148dp"
tools:layout_editor_absoluteY="266dp" />
</RelativeLayout>
Activity class
File: MainActivity.java
package example.javatpoint.com.sumoftwonumber;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
34
import android.widget.Toast;
@Override
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
addListenerOnButton();
buttonSum.setOnClickListener(new View.OnClickListener() {
@Override
String value1=edittext1.getText().toString();
35
String value2=edittext2.getText().toString();
int a=Integer.parseInt(value1);
int b=Integer.parseInt(value2);
int sum=a+b;
Toast.makeText(getApplicationContext(),String.valueOf(sum), Toast.LENGTH_L
ONG).show();
});
36
Output:
You can also create custom toast as well for example toast displaying image. You can visit next
page to see the code for custom toast.
Toast class
Toast class is used to show notification for a particular interval of time. After sometime it
disappears. It doesn't block the user interaction.
37
Constants of Toast class
There are only 2 constants of Toast class which are given below.
Constant Description
public static final int LENGTH_LONG displays view for the long duration of time.
public static final int LENGTH_SHORT displays view for the short duration of time.
Method Description
public static Toast makeText(Context context, CharSequence makes the toast containing text and
text, int duration) duration.
public void setMargin (float horizontalMargin, float changes the horizontal and vertical margin
verticalMargin) difference.
Toast.makeText(getApplicationContext(),"Hello Javatpoint",Toast.LENGTH_SHORT).show(
);
Another code:
toast.setMargin(50,50);
toast.show();
38
File: MainActivity.java
package example.javatpoint.com.toast;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.Toast;
@Override
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toast.makeText(getApplicationContext(),"Hello Javatpoint",Toast.LENGTH_SHORT).s
how();
39
Output:
activity_main.xml
Drag the component that you want to display on the main activity.
File: activity_main.xml
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/a
pk/res/android"
40
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="example.javatpoint.com.customtoast.MainActivity">
<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>
customtoast.xml
Create another xml file inside the layout directory. Here we are having ImageView and TextView
in this xml file.
File: customtoast.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
41
android:layout_height="match_parent"
android:id="@+id/custom_toast_layout"
android:orientation="vertical"
android:background="#F14E23"
>
<ImageView
android:id="@+id/custom_toast_image"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:contentDescription="Hello world"
android:src="@drawable/jtp_logo"/>
<TextView
android:id="@+id/custom_toast_message"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:contentDescription="To"
</LinearLayout>
Activity class
42
File: MainActivity.java
package example.javatpoint.com.customtoast;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;
@Override
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
LayoutInflater li = getLayoutInflater();
43
//Creating the Toast object
toast.setDuration(Toast.LENGTH_SHORT);
toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
toast.show();
Output:
44
Android ToggleButton Example
Android Toggle Button can be used to display checked/unchecked (On/Off) state on the button.
It is beneficial if user have to change the setting between two states. It can be used to On/Off
Sound, Wifi, Bluetooth etc.
Since Android 4.0, there is another type of toggle button called switch that provides slider
control.
Android ToggleButton and Switch both are the subclasses of CompoundButton class.
45
XML Attributes of ToggleButton class
Method Description
CharSequence getTextOff() Returns the text when button is not in the checked state.
CharSequence getTextOn() Returns the text for when button is in the checked state.
activity_main.xml
Drag two toggle button and one button for the layout. Now the activity_main.xml file will look
like this:
File: activity_main.xml
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/a
pk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
46
android:layout_height="match_parent"
tools:context="example.javatpoint.com.togglebutton.MainActivity">
<ToggleButton
android:id="@+id/toggleButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="8dp"
android:layout_marginTop="80dp"
android:text="ToggleButton"
android:textOff="Off"
android:textOn="On"
app:layout_constraintEnd_toStartOf="@+id/toggleButton2"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<ToggleButton
android:id="@+id/toggleButton2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginRight="60dp"
android:layout_marginTop="80dp"
android:text="ToggleButton"
47
android:textOff="Off"
android:textOn="On"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="144dp"
android:layout_marginLeft="148dp"
android:text="Submit"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintStart_toStartOf="parent" />
</android.support.constraint.ConstraintLayout>
Activity class
File: MainActivity.java
package example.javatpoint.com.togglebutton;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
48
import android.widget.Button;
import android.widget.Toast;
import android.widget.ToggleButton;
@Override
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
addListenerOnButtonClick();
//Getting the ToggleButton and Button instance from the layout xml file
toggleButton1=(ToggleButton)findViewById(R.id.toggleButton);
toggleButton2=(ToggleButton)findViewById(R.id.toggleButton2);
buttonSubmit=(Button)findViewById(R.id.button);
buttonSubmit.setOnClickListener(new View.OnClickListener(){
49
@Override
result.append("ToggleButton1 : ").append(toggleButton1.getText());
result.append("\nToggleButton2 : ").append(toggleButton2.getText());
Toast.makeText(getApplicationContext(), result.toString(),Toast.LENGTH_LONG
).show();
});
50
Output:
51
Android CheckBox Example
Android CheckBox is a type of two state button either checked or unchecked.
There can be a lot of usage of checkboxes. For example, it can be used to know the hobby of the
user, activate/deactivate the specific action etc.
52
Methods of CheckBox class
There are many inherited methods of View, TextView, and Button classes in the CheckBox class.
Some of them are as follows:
Method Description
public boolean isChecked() Returns true if it is checked otherwise false.
public void setChecked(boolean status) Changes the state of the CheckBox.
activity_main.xml
Drag the three checkboxes and one button for the layout. Now the activity_main.xml file will
look like this:
File: activity_main.xml
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/a
pk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="example.javatpoint.com.checkbox.MainActivity">
<CheckBox
android:id="@+id/checkBox"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
53
android:layout_marginLeft="144dp"
android:layout_marginTop="68dp"
android:text="Pizza"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<CheckBox
android:id="@+id/checkBox2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="144dp"
android:layout_marginTop="28dp"
android:text="Coffee"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/checkBox" />
<CheckBox
android:id="@+id/checkBox3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="144dp"
android:layout_marginTop="28dp"
android:text="Burger"
54
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/checkBox2" />
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="144dp"
android:layout_marginTop="184dp"
android:text="Order"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/checkBox3" />
</android.support.constraint.ConstraintLayout>
Activity class
File: MainActivity.java
package example.javatpoint.com.checkbox;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
55
import android.widget.CheckBox;
import android.widget.Toast;
CheckBox pizza,coffe,burger;
Button buttonOrder;
@Override
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
addListenerOnButtonClick();
pizza=(CheckBox)findViewById(R.id.checkBox);
coffe=(CheckBox)findViewById(R.id.checkBox2);
burger=(CheckBox)findViewById(R.id.checkBox3);
buttonOrder=(Button)findViewById(R.id.button);
buttonOrder.setOnClickListener(new View.OnClickListener(){
@Override
56
public void onClick(View view) {
int totalamount=0;
result.append("Selected Items:");
if(pizza.isChecked()){
result.append("\nPizza 100Rs");
totalamount+=100;
if(coffe.isChecked()){
result.append("\nCoffe 50Rs");
totalamount+=50;
if(burger.isChecked()){
result.append("\nBurger 120Rs");
totalamount+=120;
result.append("\nTotal: "+totalamount+"Rs");
});
}
57
}
Output:
58
1.Android program for addition of two numbers.
59
Ans:- Below are the steps for Creating a Simple Android Application to Add Two Numbers
STEP-2: Now go to the text and write the code for adding 3 textview,2 textedit and Button and Assign
ID to each component. Assign margin top, left, right for the location.
STEP-4: Declare few variables and the values entered in the Text Views can be read by using
an id which we have set in the XML code above.
STEP-5: Add the click listener to the Add button.
STEP-6: When the Add button has been clicked, add the values and store it into the sum
variable.
STEP-7: To show the output in the result text view, set the sum in the textview.
activity_main.xml
<!--The activity_main.xml is a layout file
an XML-based layout is a file that defines
the different widgets to be used in the UI
and the relations between those widgets
and their containers. -->
<EditText
android:id="@+id/editText_second_no"
android:layout_width="150dp"
android:layout_height="40dp"
android:layout_marginLeft="200dp"
android:layout_marginTop="90dp"
android:inputType="number"
tools:ignore="MissingConstraints" />
<!-- button for run add logic and view result -->
<Button
android:id="@+id/add_button"
android:layout_width="100dp"
android:layout_height="50dp"
android:layout_marginLeft="110dp"
android:layout_marginTop="200dp"
android:text="ADD" />
</RelativeLayout>
MainActivity.java
// Each new activity has its own layout and Java files,
// here we build the logic for adding two number
package org.geeksforgeeks.addtwonumbers;
61
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
EditText number1;
EditText number2;
Button Add_button;
TextView result;
int ans=0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
62
Ans(2):-
In my last example we have discussed about the textview and button. Text view to display any
text. In this example we are going to create an app to add two numbers.
Create an android project and use following Text Fields control to take input from the user.
I have taken two textview to display message and one textview to display output. Two plan text
field i.e EditText to take input and one button.
Design Code
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Enter First Number:-"
android:id="@+id/textView"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/editText"
android:layout_alignParentTop="true"
android:layout_toRightOf="@+id/textView" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Enter Second Number"
android:id="@+id/textView2"
android:layout_below="@+id/editText"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/editText2"
android:layout_below="@+id/editText"
android:layout_toRightOf="@+id/editText"
android:layout_toEndOf="@+id/editText" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Sum of Two No"
android:id="@+id/button"
android:layout_below="@+id/editText2"
63
android:layout_centerHorizontal="true"
android:layout_marginTop="52dp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/tv_result"
android:layout_below="@+id/button"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
Now add a click event to button. Suppose I have created sum method in java file and map this event to
click
Now execute the code and you will get following output:-
If you want to make a program for the sum two numbers in android. The code will be following.
64
EditText
TextView
Button
Toast
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
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="com.techmesolution.anand.helloworld.MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Sum Numbers"
android:id="@+id/textView" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="number"
android:ems="10"
android:layout_marginStart="29dp"
android:layout_marginTop="40dp"
android:id="@+id/num1"
android:layout_below="@+id/textView"
android:layout_alignParentStart="true"
android:hint="Enter First Number" />
<Button
android:text="Show Sum"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="47dp"
65
android:id="@+id/sum"
android:layout_below="@+id/num1"
android:layout_alignStart="@+id/num1" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="number"
android:ems="10"
android:id="@+id/num2"
android:hint="Enter Second Number"
android:layout_below="@+id/num1"
android:layout_alignStart="@+id/num1" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/showsum"
android:text="Answer"
android:layout_below="@+id/sum"
android:layout_alignStart="@+id/sum"
android:layout_marginTop="19dp" />
</RelativeLayout>
MainActivity.java
package com.techmesolution.anand.helloworld;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
sum.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v) {
String value1=num1.getText().toString();
String value2=num2.getText().toString();
int a = Integer.parseInt(value1);
int b = Integer.parseInt(value2);
int sum = a+b;
answer.setText(Integer.toString(sum));
Toast.makeText(getApplicationContext(), String.valueOf(sum),
Toast.LENGTH_LONG).show();
}
});
}
}
Ans(another):-
In order to develop an Android App for adding two numbers first, thing we have to do is take
two inputs numbers from the user and by clicking SUM buttons which will add these two
numbers.
Please follow the steps below for creating an Android app to add two numbers:
Step 1) First, go to the text field here and select the number fields for adding two numbers.
Step 2) You can double-click the text box and add the text to this text field but right now text
field is not required because we are not going to display any text on these text boxes but you
the id is important. Id is the unique id which differentiates one phone from another. For
example, this Edit Text id 1 is the id of the first number text and Edit Text id 2 is the id of
the second added text.
Step 3) Now to show this number text or edit we can provide the hint to this text box so for that
you just select this edit text and go to the property called a hint. So there's a property called
hint and here we can provide the hint to the user that what he’s expected to enter here. The
67
hints we assign will appear on our text boxes but it will not appear as a text, it will appear as
a hint.Whatever text you write here will be provided as a hint.
Step 4) Now to add these numbers and to display the message, we can display message by these
plain text views or any other text views from here. We can adjust the length of the text view.
For now, let’s take a large text view.
Step 5) We are going to add one more button to our activity so that whenever this button is
clicked, we should be able to see the results. Therefore in the widgets, just drag and drop the
button.
Step 6) Now our design is complete. We have two text boxes. We have a result text box or
TextEdit or TextView and we have our button.We can also see them in the component tree.
Step 7) Now everything is done, so we will go to our java folder and in the java folder we are
going to go inside the MainActivity.
Step 10) Now how can we tell this button that we want to call this method when we press this
button. So what we can do is just select the button and in the Properties, we have to find
property called onClick and once you are on click property here, you can just click the combo
box and we will be able to see onButtonclick method automatically appearing there. So now
when we go into the design view, you will see the onButtonclick method.
Step 11) Now whenever we run the program, we will be the result in our emulator. Now in order
to check the application please enter the Number1 and Number2 and click sum, see the result.
Step 12) Now In a similar way, you can use this activity to calculate the subtraction, division or
multiplication of these two numbers. So you can add some more methods and some more buttons
and you can whatever you enter here, you can click subtraction button, or addition button or
multiplication button or division button. That’ll give you the same result. So this application you
can simply extend it to arithmetic operations, different arithmetic operations with the numbers.
Another Ans:-
In this tutorial, we are creating an application to add two numbers(Addition). This tutorial helps
beginners to create a calculator application. By understanding, this tutorial will help you to create
other methods like subtract, multiplication, division.
In our tutorial, we simply created two EditTexts one is used to get 1 number from the user and
another is used to get another number from the user. After that, we added a button when a user
clicks the button, an addition of two EditTexts numbers will show as Toast message.
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="16dp"
tools:context=".MainActivity">
<EditText
android:id="@+id/et1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter number one"
android:inputType="numberDecimal" />
<EditText
android:id="@+id/et2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter number two"
69
android:inputType="numberDecimal" />
<Button
android:id="@+id/btnAdd"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Add" />
</LinearLayout>
MainActivity.java
package com.techyour.test;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnAdd.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
int first =
Integer.valueOf(et1.getText().toString().trim());//converting string to int
int second = Integer.valueOf(et2.getText().toString().trim());
int sum = first + second;
Toast.makeText(MainActivity.this, String.valueOf(sum),
Toast.LENGTH_SHORT).show();
et1.getText().clear();
et2.getText().clear();
}
});
}
}
Code Explanation:
We added android:inputType=”numberDecimal” attribute to two EditTexts which is used to get
only decimal numbers from the user and decimal number keyboard layout will be shown.
Integer.valueOf(et1.getText().toString().trim()); means get the EditText and removes the empty
spaces and finally converts the String to Integer.
70
et1.getText().clear(); this will clears the EditText text.
In our code, we used java string trim() method which eliminates leading and trailing spaces and
return omitted string.
package com.droidacid.apticalc.aptitudes;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import com.droidacid.apticalc.R;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.apti_factorial);
initialize();
}
long factorial = 1;
try {
factorial = Long.parseLong(number.getText().toString());
for(int i=factorial-1; i>0; i--){
factorial = i * factorial;
}
} catch (NumberFormatException e) {
Toast.makeText(this, "Incorrect Input", Toast.LENGTH_LONG).show();
} finally {}
return factorial;
71
}
@Override
public void onClick(View v) {
answer.setText("Factorial of " + number.getText().toString() + " is : " +
calcFactorial());
}
Then select the Minimum SDK as shown below and click Next.
Then delete the code which is there and type the code as given below.
<TextView
72
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_x="20dp"
android:layout_y="110dp"
android:text="Enter Rollno:"
android:textSize="20sp" />
<EditText
android:id="@+id/Rollno"
android:layout_width="150dp"
android:layout_height="wrap_content"
android:layout_x="175dp"
android:layout_y="100dp"
android:inputType="number"
android:textSize="20sp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_x="20dp"
android:layout_y="160dp"
android:text="Enter Name:"
android:textSize="20sp" />
<EditText
android:id="@+id/Name"
android:layout_width="150dp"
android:layout_height="wrap_content"
android:layout_x="175dp"
android:layout_y="150dp"
android:inputType="text"
android:textSize="20sp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_x="20dp"
android:layout_y="210dp"
android:text="Enter Marks:"
android:textSize="20sp" />
<EditText
android:id="@+id/Marks"
android:layout_width="150dp"
android:layout_height="wrap_content"
android:layout_x="175dp"
android:layout_y="200dp"
android:inputType="number"
android:textSize="20sp" />
<Button
android:id="@+id/Insert"
android:layout_width="150dp"
android:layout_height="wrap_content"
android:layout_x="25dp"
73
android:layout_y="300dp"
android:text="Insert"
android:textSize="30dp" />
<Button
android:id="@+id/Delete"
android:layout_width="150dp"
android:layout_height="wrap_content"
android:layout_x="200dp"
android:layout_y="300dp"
android:text="Delete"
android:textSize="30dp" />
<Button
android:id="@+id/Update"
android:layout_width="150dp"
android:layout_height="wrap_content"
android:layout_x="25dp"
android:layout_y="400dp"
android:text="Update"
android:textSize="30dp" />
<Button
android:id="@+id/View"
android:layout_width="150dp"
android:layout_height="wrap_content"
android:layout_x="200dp"
android:layout_y="400dp"
android:text="View"
android:textSize="30dp" />
<Button
android:id="@+id/ViewAll"
android:layout_width="200dp"
android:layout_height="wrap_content"
android:layout_x="100dp"
android:layout_y="500dp"
android:text="View All"
android:textSize="30dp" />
</AbsoluteLayout>
Now click on Design and your application will look as given below.
Then delete the code which is there and type the code as given below.
74
Code for MainActivity.java:
package com.example.exno5;
import android.app.Activity;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
Rollno=(EditText)findViewById(R.id.Rollno);
Name=(EditText)findViewById(R.id.Name);
Marks=(EditText)findViewById(R.id.Marks);
Insert=(Button)findViewById(R.id.Insert);
Delete=(Button)findViewById(R.id.Delete);
Update=(Button)findViewById(R.id.Update);
View=(Button)findViewById(R.id.View);
ViewAll=(Button)findViewById(R.id.ViewAll);
Insert.setOnClickListener(this);
Delete.setOnClickListener(this);
Update.setOnClickListener(this);
View.setOnClickListener(this);
ViewAll.setOnClickListener(this);
76
// Display a record from the Student table
if(view==View)
{
// Checking for empty roll number
if(Rollno.getText().toString().trim().length()==0)
{
showMessage("Error", "Please enter Rollno");
return;
}
Cursor c=db.rawQuery("SELECT * FROM student WHERE
rollno='"+Rollno.getText()+"'", null);
if(c.moveToFirst())
{
Name.setText(c.getString(1));
Marks.setText(c.getString(2));
}
else
{
showMessage("Error", "Invalid Rollno");
clearText();
}
}
// Displaying all the records
if(view==ViewAll)
{
Cursor c=db.rawQuery("SELECT * FROM student", null);
if(c.getCount()==0)
{
showMessage("Error", "No records found");
return;
}
StringBuffer buffer=new StringBuffer();
while(c.moveToNext())
{
buffer.append("Rollno: "+c.getString(0)+"\n");
buffer.append("Name: "+c.getString(1)+"\n");
buffer.append("Marks: "+c.getString(2)+"\n\n");
}
showMessage("Student Details", buffer.toString());
}
}
public void showMessage(String title,String message)
{
Builder builder=new Builder(this);
builder.setCancelable(true);
builder.setTitle(title);
builder.setMessage(message);
builder.show();
}
public void clearText()
{
Rollno.setText("");
Name.setText("");
Marks.setText("");
Rollno.requestFocus();
}
77
}
So now the Coding part is also completed.
Now run the application to see the output.
78
79