Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 53

TextField

A Text field allows the user to type text into your app.

It can be either single line or multi-line. Touching a text filed places the cursor and automatically displays the keyboard.

In addition to typing, text fields allow for a variety of other activities, such as text selection (cut, copy, paste) and data
look-up via auto-completion.

You can specify the type of keyboard you want for your EditText object with the andoid:inputType attribute. For Example,
if you want the user to input a Phone number, you should use the phone input type.
There are several different input types available for different situations. Here are some of the
common values for android:inputType:

text – Normal text keyboard

textEmailAddress – Normal text keyboard with the @ character

textUri – Normal text keyboard with / character

number – Basic number keypad

phone – Phone-style keypad.

Keyboard Behaviour Controls


The android:inputType also allows you to specify certain keyboard behaviors, such as whether to capitalize all the
new words or use features like auto-complete and spelling suggestions.

textCapSentences – first letter of each new sentences


textCapWords – every word (good for tiles or person name)
textautoCorrect corrects commonly misspelled words
textPassword – character entered turns into dot
textMultiLine – allow user to input long strings of text that include line breaks
Wrap_content, fill_parent,

Wrap content
The component just want to display
big enough to enclose its content only.
Both layout width and height can set

Fill parent
Width will be adjusted to height of activity

In this method the component wants to


display as big as its parent
(parent is activity here)
(fills the remaining space)

Match parent also works in the similar way

Adjusting the width and height of the widget


Watch video for more
details:

https://www.youtube.com/
watch?v=zhszwkcay2A
A device-independent pixel (also: density-independent pixel, dip, dp) is a physical unit of measurement based on a
coordinate system held by a computer and represents an abstraction of a pixel for use by an application that an underlying
system then converts to physical pixels.

A typical use is to allow mobile device software to scale the display of information and user interaction to different screen
sizes.
The abstraction allows an application to work in pixels as a measurement, while the underlying graphics system converts the
abstract pixel measurements of the application into real pixel measurements appropriate to the particular device.

As dp is a physical unit it has an absolute value which can be measured in traditional units, e.g. for Android devices 1 dp equals
1/160 of inch or 0.15875 mm.

While traditional pixels only refer to the display of information,


device-independent pixels may also be used to measure user
input such as input on a touch screen device.
Scale independent pixel

Used for text

The Android system scales these for the current screen density and the user’s system-wide
Scaling factor for text selected in the settings app.
Dimensions in Android
Formatting Text
TEXT VIEW : Text and ID for further Reference is important

Try some of the following properties

Text size (in sp - scaled independently)


Text color
Background
Padding 10 (in dp - Density-independent pixel)
Toast in Android
• To display a message in android , you
need to Import a library called Toast .
• import android.widget.Toast;

• Toast is a library with which we can


show Messages.

• In android Messages are called toast


• Write a function and use toast to
display a message and call that
function on button click event.

public void ButtonClick(View v) {


Toast.makeText(MainActivity.this,“Type Message here",Toast.LENGTH_LONG).show();
}
Name of the activity

* Call this method Buttonclick In the onClick event in property window of button
On click of a button display the content typed in the text field as message using toast

- Insert a plain text


- Insert a button
- In MainActivity.java write the following code

public void ButtonClick(View v) {


// declaration for the edit text element
EditText t1 = (EditText)findViewById(R.id.editText);

Toast.makeText(MainActivity.this,t1.getText(),Toast.LENGTH_LONG).show();
}

- Call this method Buttonclick In the onClick event in


property window of button
Practice Assignment Sample screen

Try to create a basic calculator


With minimum four basic arithmetic operations
( + - * /)

Numbers can be input from the user


Use 4 individual buttons for each operation
Android - Event Handling

Events are a useful way to collect data about a user's interaction with
interactive components of Applications.

Like button presses or screen touch etc. The Android framework maintains an
event queue as first-in, first-out (FIFO) basis. You can capture these events in
your program and take appropriate action as per requirements.
There are following three concepts related to Android Event Management −

Event Listeners − An event listener is an interface in the View class that contains
a single callback method. These methods will be called by the Android
framework when the View to which the listener has been registered is triggered
by user interaction with the item in the UI.

Event Listeners Registration − Event Registration is the process by which an


Event Handler gets registered with an Event Listener so that the handler is called
when the Event Listener fires the event.

Event Handlers − When an event happens and we have registered an event


listener for the event, the event listener calls the Event Handlers, which is the
method that actually handles the event.
There are many more event listeners available as a part of View class like
OnHoverListener, OnDragListener etc which may be needed for your application.
So It is recommend to refer official documentation for Android application development
in case you are going to develop a sophisticated apps.
Event Listeners Registration
Event Registration is the process by which an Event Handler gets
registered with an Event Listener so that the handler is called when
the Event Listener fires the event.

Though there are several tricky ways to register your event listener
for any event, only top 3 ways are listed here, out of which you can
use any of them based on the situation.

1. Using an Anonymous Inner Class


2. Activity class implements the Listener interface.
3.Using Layout file activity_main.xml to specify event handler
directly. (easy one)
Method 1 – with event listener - 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.button1);

b1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
TextView txtView =(TextView)findViewById(R.id.textView);
txtView.setTextSize(25);
}
}
);
}
}
Method 2 – Using Layout file activity_main.xml

public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void ButtonClick(View v) {
// declaration for the edit text element
EditText t1 = (EditText)findViewById(R.id.editText);
t1.setTextSize(25);
}

- Call this method Buttonclick In the onClick event in


property window of button
Event listeners – Two button – Increase and decrease
CHECKBOX
Checkbox is a type of two state button either checked or unchecked,
For example it can be used to know the hobby of a the user,
activate /deactivate the specific action etc.

Checkbox Class
The android.widget.CheckBox class provides the facility of creating
the CheckBoxes.

Methods of ChekBox class


1- Public boolean isChecked() returns true if it is checked otherwisefalse.
2- public void setchecked(boolean status) changes the state of the
CheckBox.
CheckBox
Generally we use check box whenever we want to choose a list of items.
For example : selecting list of grocery Items , or selecting favorite food item
Basically whenever we have to select multiple items then checkbox will be used.
1. Add 3 checkboxes to your layout
2. Add a button
3. Select all three buttons and change the layout width as – fill_parent in properties box
4. Rename all the three buttons and give proper id for all button
(you can make any checkbox as default checked)
5. Open MainActivity.java
6. Declare all the 3 checkbox and the 1 button variable
7. Create a method (public , no argument and does not return anything)
8. Cast all check box and button
9. Add listener – for the button
10. In OnClick method , create a buffer to store the result (which check box is checked.)
11. Display a toast
12. Call the method in the onCreate function.

* On button click event we can check which check box is selected


public class MainActivity extends AppCompatActivity {
private CheckBox check1, check2,check3;
private Button button_sel;

@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layiout.activity_main);
addListenerOnButton();
}
public void addListenerOnButton(){
// cast all checkbox and button
check1=(CheckBox)findViewById(R.id.checkBox_ic);
check2=(CheckBox)findViewById(R.id.checkBox_ch);
check3=(CheckBox)findViewById(R.id.checkBox_fr);
button_sel=(Button)findViewById(R.id.button);

// add listener to the button


button_sel.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
StringBuffer result = new StringBuffer();
result.append("Ice cream : ").append(check1.isChecked());
result.append("Chocolate : ").append(check2.isChecked());
result.append("Fruits : ").append(check3.isChecked());

Toast.makeText(MainActivity.this,result.toString(),Toast.LENGTH
_LONG).show();

// tostring() because result is buffer

}
}
);
}

} See also - CheckBox Example 2


Second CHECKBOX Example2
Radio Button
- When you want to give user a choice of selecting any one option use radio button.
- Use Container - RadioGroup to keep all your Radio button inside this.
(used to group radio button , whatever radio button kept inside this will be grouped
together , logic behind grouping is , only able to select only one option out of
multiple
radio button).

Use radio button inside container


Use button outside the container.
Change the property of the container to – wrap content
Rename the radio buttons
Declaration of variable
// declare variables, need only one radio button as we need only one selection among
//all radio button

private static RadioGroup radio_g; // variable for radio group


private static RadioButton radio_b; // variable for selected radio button
private static Button button_sub; // variable for button
FILE : RB1
public class MainActivity extends AppCompatActivity {
MainActivity.java
// variable declaration
private static RadioGroup radio_g;
private static RadioButton rb1;
private static Button button_sub;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
onclickListenerButton(); // calling the function
}
public void onclickListenerButton(){
//casting the radiobutton and button
radio_g=(RadioGroup)findViewById(R.id.RG);
button_sub=(Button)findViewById(R.id.b1);
button_sub.setOnClickListener(

new View.OnClickListener() {
@Override

public void onClick(View v) {


int selected_id=radio_g.getCheckedRadioButtonId();
rb1=(RadioButton)findViewById(selected_id);
Toast.makeText(MainActivity.this,
rb1.getText().toString(),Toast.LENGTH_LONG).show();
}
}
);
}
Import Images to Android Studio

You can drag and drop images to drawable folder


Use IMAGE VIEW
Write a function to change the image to another

// change the image of the Imageview


public void catClick(View view) {
ImageView image = (ImageView) findViewById(R.id.catImageView);
image.setImageResource(R.drawable.cat2);
}
Change image display properties in: scaleType :
Import images to @drawable
You can copy paste the image
After that
Try the following code and explore more option in the ImageView

<ImageView
android:src="@drawable/cat"
android:layout_width=“wrap_content"
android:layout_height=“wrap_content"
android:id="@+id/imageView"
android:scaleType="centerCrop"
android:layout_below="@+id/textView"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginTop="75dp" />

• Try to Change the height and width to be a fixed value


• Try to change the scaletype between center and centercrop
Input Controls
Input controls are the interactive components in your app’s user
interface.

Android provides a wide variety of controls you can use in your UI,
such as buttons, text fields, seek bars, checkboxes, zoon buttons,
toggle buttons and many more.

Adding an input control to your UI as simple as adding an XML


element to your XML layout.
Some of the common Android UI controls are :
Layout with text field and a button

<?xml version="1.0" encoding="utf-8"?>


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >

<TextView android:id="@+id/text"
android:layout_width="wrap_content“
android:layout_height="wrap_content"
android:text="I am a TextView" />

<Button android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="I am a Button" />

</LinearLayout>
Buttons
Android buttons are that GUI components which are sensible to taps (click) by the User.

Android Buttons can be of two types:


1. Buttons with text
2. Button with Images, Button which contains images are also called ImageButtons.

Buttons:
A standard Android button with text is represented by android Class
android.widget.Button
Button instance can be inserted into GUI either through .XML file or programmatically in
.java file.

android:id="@+id/button - id provides a unique identification to a UI element.


Thus when thre are two or more buttons. It is this id which helps us to differentitate
between the two in the java code (usually done by findViewByID() method).

android:layout_width and android:layout_height – It defines the size the UI element


should occupy.

android:text="I am a Button“ – Defines the text which the UI element should display
Adding a button programmatically:

public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

Button button = new Button(this);


button.setText(“hello”);

RelativeLayout relativeLayout= (RelativeLayout) findViewById(R.id.rootlayout);


relativeLayout.addView(button);

1 Create the instance of the Button class by passing the current context as this.
2 Set the text which the button should display.
3 Create the object of the ViewGroup (Layout) in which the button needs to be placed.
4 Find the layout by using findViewByid() method.
5 Add the button to the layout by addView function

* You can also add an image with button by using android:drawableLeft property.
Try Yourself

Toggle Button Toast


Radio Button AutoCompleteTextview
CheckBox Alertdialog
Spinners checkedTextView
RatingBar TextSwitcher
ProgressBar ImageSwitcher
Datepicker AdapterViewFlipper.
Timepicker
Intent
What are intents?

Android application components can connect to other Android applications.


This connection is based on a task description represented by an Intent object.

Android Intent is the message that is passed between components such as activities,


content providers, broadcast receivers, services etc.
Intents are asynchronous messages which allow application components to request
functionality from other Android components. Intents allow you to interact with
components from the same applications as well as with components contributed by
other applications.

For example, an activity can start an external activity for taking a picture.

Intents are objects of the android.content.Intent type. Your code can send them to the Android system
defining the components you are targeting.

For example, via the startActivity() method you can define that the intent should be used to start an
activity.

An intent can contain data via a Bundle. This data can be used by the receiving component.
In Android the reuse of other application components is a concept known as task. An application can access other
Android components to achieve a task.

For example, from a component of your application you can trigger another component in the Android system, which
manages photos, even if this component is not part of your application. In this component you select a photo and
return to your application to use the selected photo.

Android intents are mainly used to:

• Start the service


• Launch an activity
• Display a web page
• Display a list of contacts
• Broadcast a message
• Dial a phone call etc.
Starting activities or services
To start an activity, use the method startActivity(intent).
This method is defined on the Context object which Activity extends.

The following code demonstrates how you can start another activity via an intent.

# Start the activity connect to the


# specified class

Intent i = new Intent(this, ActivityTwo.class); startActivity(i);

Activities which are started by other Android activities are called sub-activities. This wording makes it easier
to describe which activity is meant.
To start a services via intents, use the startService(Intent) method call.
There are two types of intents in android: implicit and explicit.

Implicit Intent
Implicit Intent doesn't specify the component. In such case, intent provides information of available
components provided by the system that is to be invoked.
For example, you may write the following code to view the webpage.

Intent intent=new Intent(Intent.ACTION_VIEW);  
intent.setData(Uri.parse("http://www.vinay.in"));  
startActivity(intent);  

Explicit Intent
Explicit Intent specifies the component. In such case, intent provides the external class to be invoked.

Intent i = new Intent(getApplicationContext(), ActivityTwo.class);  
startActivity(i);  
Sending out explicit or implicit intents
Android supports explicit and implicit intents.
An application can define the target component directly in the intent (explicit intent) or ask the Android
system to evaluate registered components based on the intent data(implicit intents).

Explicit intents explicitly define the component which should be called by the Android system, by using the
Java class as identifier.
Explicit intents are typically used within an application as the classes in an application are controlled by the
application developer. The following shows how to create an explicit intent and send it to the Android
system to start an activity.

Intent i = new Intent(this, ActivityTwo.class);


i.putExtra("Value1", "This value one for ActivityTwo ");
i.putExtra("Value2", "This value two ActivityTwo");
Implicit intents specify the action which should be performed and optionally data which provides content for the
action. If an implicit intent is sent to the Android system, it searches for all components which are registered for
the specific action and the fitting data type.

If only one component is found, Android starts this component directly. If several components are identified by the
Android system, the user will get a selection dialog and can decide which component should be used for the intent.

For example, the following tells the Android system to view a webpage.
All installed web browsers should be registered to the corresponding intent data via an intent filter.

Intent i = new Intent(Intent.ACTION_VIEW,


Uri.parse("http://www.vogella.com"));
startActivity(i);
Intents as event triggers
Intents can be used to send broadcast messages into the Android system. A broadcast receiver can
register to an event and is notified if such an event is sent.

Your application can register to system events, e.g., a new email has arrived, system boot is complete
or a phone call is received and react accordingly.
Try it yourself with sample code

Implicit Intent use for the following

1. Open Email app on click on of a button

2. Open MAP based on the click ( show the specified location)

3. Phone call App – Accept number and call that number

4. Dial a phone number directly

Refer the word file for code exmaple


Adding Custom Toast
Two ways –
public class MainActivity extends Activity {   1 . By creating another xml
     @Override   file ,defining layout, inflate
        public void onCreate(Bundle savedInstanceState) {   2. using options of toast in the
            super.onCreate(savedInstanceState);   mainActivity.java file
            setContentView(R.layout.activity_main);   itself
       //Creating the LayoutInflater instance  
            LayoutInflater li = getLayoutInflater();  
        //Getting the View object as defined in the customtoast.xml file  
            View layout = li.inflate(R.layout.customtoast,  
              (ViewGroup) findViewById(R.id.custom_toast_layout));  
       //Creating the Toast object   
            Toast toast = new Toast(getApplicationContext());  
            toast.setDuration(Toast.LENGTH_SHORT);  
            toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);  
            toast.setView(layout); //setting the view of custom toast layout  
            toast.show();  
        }  
        @Override  
        public boolean onCreateOptionsMenu(Menu menu) {  
            getMenuInflater().inflate(R.menu.activity_main, menu);  
            return true;  
        }  
Custom Toast

- A toast is for showing messages for short interval of time.


- You would like to customize it with adding image to it and
changing size, color of the message text.
- If that is all, you want to do, then no need to make a separate
layout and inflate it to the Toast instance.
- The default Toast's view contains a TextView for showing
messages on it.
- So, if we have the resource id reference of that TextView, we can
play with it.

Positioning your Toast


A standard toast notification appears near the bottom of the screen, centered
horizontally. You can change this position with the setGravity(int, int, int) method.
This accepts three parameters: a Gravity constant, an x-position offset, and a y-
position offset.
Custom Toast
example

You might also like