Starting With Android Program
Starting With Android Program
View Group: A view group is a type of view that can contain other
views.
A layout is a special type of view called a view group.
All layouts are subclasses of the android.view.ViewGroup class.
All layouts and GUI components share this common functionality.
Linear Layout
Relative Layout
Constraint Layout
Frame Layout
Web View
List View
Grid View
String.xml and Color.xml
strings.xml is a String resource file. It includes Strings such as the app’s
name and any default text values. Other files such as layouts and
activities can look up text values from here.
How do you use String resources?
In order to use a String resource in your layout, there are two things
you need to do:
1) Create the String resource by adding it to strings.xml.
2) Use the String resource in your layout.
To do this, use Android Studio’s explorer to find the file strings.
xml in the app/src/main/res/values folder. Then open it by double-
clicking on it.
<resources>
<string name=“age">Enter your Age</string>
</resources>
To define what type of data you’re expecting the user to enter we can use
android:inputType="number“
You can specify multiple input types using the | character
E.G android:inputType="textCapSentences|textAutoCorrect"
Submit (Button)
In Android, padding attribute applied to the parent(root layout) looks the same
as margin attribute applied to the child(views inside the layout).
Gravity: controls the position of a view’s contents. We can achieve this by using android:gravity
attribute.
The android:gravity attribute lets you specify how you want to position the contents of a view inside
the view.
<LinearLayout ... >
...
<Button
android:layout_width="match_parent"
android:layout_height=“wrap_content"
android:gravity="top"
android:hint="@string/message" />
...
</LinearLayout>
Displays the text inside the Button at the top of the Button
Layout_gravity: controls the position of a view within a layout. We can achieve this by using
android:layout_gravity attribute.
android:layout_gravity deals with the placement of the view itself, and lets you control where views
appear in their available space.
Android:layout_gravity=“end”
Linear Layout supports assigning a weight to individual children with
the android:layout_weight attribute.
This attribute assigns an "importance" value to a view in terms of how
much space it should occupy on the screen. A larger weight value
allows it to expand to fill any remaining space in the parent view.
Try to develop the layout the next Layout
Linear Layout Example
Relative Layout
android:layout_alignParentTop
If “true”, makes the top edge of this view match the top edge of the
parent
android:layout_centerVertical
If “true”, centers this child vertically within its parent
android:layout_below
Positions the top edge of this view below the view specified with a
resource ID.
android:layout_toRightOf
Positions the left edge of this view to the right of the view specified with
a resource ID.
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="16dp"
android:paddingRight="16dp" >
<TextView
android:id="@+id/sign_in"
android:layout_width=“wrap_content" Sign in (TextView)
android:layout_height="wrap_content“
android:layout_alignParentTop=“true”
android:layout_centerHorizontal=“true” (TextView)UserName: enter user name(Edit Text)
/> (TextView)Password: enter Password(Edit Text)
<TextView
android:id="@+id/user_name"
android:layout_width=“wrap_content" Login
android:layout_height="wrap_content"
android:layout_below="@id/sign_in"
android:layout_alignParentLeft="true"
android:layout_toLeftOf="@+id/txt_user" />
<TextView
android:id="@id/password"
android:layout_width=“wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/user_name"
/>
<Button
android:layout_width="96dp"
android:layout_height="wrap_content"
android:layout_below="@id/pasword"
android:layout_centerHorizontal="true"
/>
Frame Layout
We use Frame Layout when we want our views to overlap. For
instance suppose we want to display an image with some text
overlaid on top of it.
Frame Layout stack their views on top of each other.
Frame Layout is designed to block out an area on the screen to
display a single item
We define Frame Layout using <FrameLayout> element.
The android:layout_width and android:layout_height attributes are
mandatory
it can be difficult to organize child views in a way that's scalable to
different screen sizes without the children overlapping each
other. But we can control their position using android:layout_gravity.
Constraint Layout
Constraint Layout: Constraint Layout is a View Group (i.e. a view that
holds other views) which allows you to create large and complex
layouts with a flat view hierarchy
Allows you to position and size widgets in a very flexible way. It was
created to help reduce the nesting of views and also improve the
performance of layout files.
Advantage
you can perform animations on your Constraint Layout views with very
little code.
You can build your complete layout with simple drag-and-drop on
the Android Studio design ed
You can control what happens to a group of widgets through a single
line of code.
Dynamically position UI elements onscreen in relation to other elements.
Constraint Layout improve performance over other layout
Important points to use constraint Layout
Your Android Studio version must be 2.3 or higher.
You must first include the ConstraintLayout’s support library.
You must have at least one vertical and one horizontal constraints.
XML
Activity code
@Override
<menu xmlns:android="http://schemas.android.com/apk/res/and public boolean
roid"> onCreateOptionsMenu(Menu
menu) {
getMenuInflater().inflate(R.menu.a
<item android:id="@+id/search" ctivity_main, menu);
android:title="@string/search"
return true;
/>
}
<item android:id="@+id/settings"
android:title="@string/settings" />
</menu>
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
switch (id){
case R.id.search:
Toast.makeText(getApplicationContext(),“search Selected",Toast.LENGTH_LONG).show();
return true;
case R.id.settings:
Toast.makeText(getApplicationContext(),“settings Selected",Toast.LENGTH_LONG).show();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
Context Menu: is like a floating menu and that appears when the
user performs a long press or click on an element and it is useful to
implement actions that affect the selected content or context
frame.
Mostly used in List views and Grid views
The views which are used to show the context menu on long-press
need to registered using registerForContextMenu(view)
we need to override onCreateContextMenu() in our Activity
or Fragment to display the context menu on the view.
we can handle a context menu item click events using the
onContextItemSelected() method.
Context Menu Xml & Activity
Xml
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="@+id/sms"
android:title="@string/send_sms"
/>
<item android:id="@+id/copy"
android:title="@string/copy" />
</menu>
@override
Activity Public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenuInfo menuInfo){
Super.onCreateContextMenu(menu,v,menuInfo);
MenuInflater inflater= getMenuInflator();
Inflator.inflate(R.menu.context_menu, menu);
}
Cont’d
We will create List View and register it on our ContextMenu
String names={“”,””,””}
ListView list;
list= (ListView) findViewById(R.id.listView);
ArrayAdapter<String> adapter=new ArrayAdapter<String>(this,android.R.layout.
simple_list_item_1,names);
listView.setAdapter(adapter);
registerForContextMenu(listView); // Register the ListView for Context menu
Next we can handle a context menu item click events using the
onContextItemSelected() method.
@Override
public boolean onContextItemSelected(MenuItem item){
if(item.getItemId()==R.id.sms){
Toast.makeText(getApplicationContext(),“sms code",Toast.LENGTH_LONG).sho
w();
}
else if(item.getItemId()==R.id.copy){
Toast.makeText(getApplicationContext(),“copy code",Toast.LENGTH_LONG).sho
w();
}else{
return false;
}
return true;
}
}
Popup Menu: displays a list of items in a modal popup window that
is anchored to the view. The popup menu will appear below
the view if there is a room or above the view in case if there is no
space and it will be closed automatically when we touch outside of
the popup.it is useful to provide an overflow of actions that related
to specific content.
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:id="@+id/one"
android:title="One" />
<item
android:id="@+id/two"
android:title="Two"/>
<item
android:id="@+id/three"
android:title="Three"/>
</menu>
@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());
onRestart() When your activity has been stopped but just before it gets onStart()
started again.
onStart() When your activity is becoming visible. onResume() or
onStop()
onResume() When your activity is in the foreground. onPause()
onPause() When your activity is no longer in the foreground because onResume() or
another activity is resuming onStop()
On Destroy
theactivity is finishing (due to the user completely dismissing
the activity)
the
system is temporarily destroying the activity due to a
configuration change (such as device rotation, language)
Stop Watch Activity
Layout
Cont’d
Use
Linear Layout
Relative Layout or
Constraint Layout
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
Activity code public class StopwatchActivity extends Activity {
private int seconds = 0;
private boolean running;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_stopwatch);
}
//Start the stopwatch running when the Start button is clicked.
public void onClickStart(View view) {
running = true;
}
//Stop the stopwatch running when the Stop button is clicked.
public void onClickStop(View view) {
running = false;
}
//Reset the stopwatch when the Reset button is clicked.
public void onClickReset(View view) {
running = false;
seconds = 0;
}
}
A Handler is an Android class you can use to schedule code that should
be run at some point in the future private void runTimer() {
To use the Handler, you wrap the code you wish to final TextView timeView =
(TextView)findViewById(R.id.time_view
schedule in a Runnable object, and then use the );
Handler post() and postDelayed() methods to specify final Handler handler = new Handler();
handler.post(new Runnable() {
when you want the code to run. @Override
The post() method posts code that needs to be run as public void run() {
int hours = seconds/3600;
soon as possible (which is usually almost immediately). int minutes = (seconds%3600)/60;
This method takes one parameter, an object of type int secs = seconds%60;
String time =
Runnable. String.format(Locale.getDefault(),
The postDelayed() method works in a similar way to the "%d:%02d:%02d", hours, minutes, secs);
timeView.setText(time);
post() method except that you use it to post code that
if (running) {
should be run in the future seconds++;
}
Two parameters: A Runnable and a long
handler.postDelayed(this, 1000);
}
});
Cont’d
Your Activity inherits the lifecycle methods
Context: An interface to global information
about the application environment allows access
to application resources, classes, and operations.
Activity: The Activity class implements default
versions of the lifecycle methods. It also defines
methods such as findViewById(Int) and
setContentView(View).
States of an Activity
The main state of an activity is when it’s running or active. An activity is running
when it’s in the foreground of the screen, it has the focus, and the
user can interact with it. Activity
Launched
The onCreate() method gets called immediately after your
activity is launched. This method is where you do all your normal
activity setup such as calling setContentView()
The onDestroy() method is the final call you get before the
Activity
activity is destroyed. There are a number of situations in which
Running
an activity can get destroyed
—for example, if it’s been told to finish, if the activity is being recreated due to a
change in device configuration, or if Android has decided to destroy the activity in
order to save space.
Activity
Destroyed
Save the current state (onCreate/
onDestroy)
When we change device configuration, like orientation the app will loss
local variables used by the activity.
How we restore the value?
We need to implement the onSaveInstanceState() method. This
method gets called before the activity gets destroyed, which means
you get an opportunity to save any values you want to retain before
they get lost.
onSaveInstanceState() method takes one parameter, a Bundle. A
Bundle allows you to gather together different types of data into a
single object.
public void onSaveInstanceState(Bundle savedInstanceState) {
}
Add this two codes in the activity
savedInstanceState.putBoolean("wasRunning", wasRunning);
wasRunning = savedInstanceState.getBoolean("wasRunning");
Implement onPause() to stop the
timer
When an activity is visible but doesn’t have the focus, the activity is
Paused. This can happen if another activity appears on top of your
activity that isn’t full-size or that’s transparent.
@Override
@Override
protected void onResume() {
protected void onPause() {
super.onResume();
super.onPause();
if (wasRunning) {
wasRunning = running;
running = true;
running = false;
}
}
}
Conclusion
Properly use the Activity Life cycle can help ensure that your app
avoids:
Consuming valuable system resources when the user is not
actively using it.
Losing the user’s progress if they leave your app and return to it
at a later time.
Crashing or losing the user’s progress when the screen rotates
between landscape and portrait orientation or switches to
another app while using your app.
Intent
Apps can contain more than one Activity
For example, if your app is simple it can display a list of recipes.
But most of time, you will need to use multiple activities one for
displaying the list of recipes and another for adding a single recipe.
You start an activity by creating an intent and using it in the
startActivity() method.
Android Intent is the message that is passed between components
such as activities, content providers, broadcast receivers, services
etc. The dictionary meaning of intent is intention or purpose. So, it
can be described as the intention to do action.
A messaging app could start an activity in a camera app to take a
picture, then start an activity in an email app to let the user share the
picture in email.
Intent Applications
Intent intent = new If you always want your user to choose an Activity
Intent(Intent.ACTION_SEND); Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("text/plain"); intent.setType("text/plain");
intent.putExtra(Intent.EXTRA_TEXT, intent.putExtra(Intent.EXTRA_TEXT, "Hello");
"Hello"); String chooserTitle = getString(R.string.chooser);
startActivity(intent) Intent chosen= Intent.createChooser(intent,chooserTitle);
startActivity(chosen);
Explicit Intent
Explicit intent: Explicit Intent specifies the component. In such case,
intent provides the external class to be invoked in our app. We are
explicitly tell Android which class is expected to run.
Explicit Intent work internally within an application to perform navigation
and data transfer.
Intent i = new Intent(getApplicationContext(), ActivityTwo.class);
startActivity(i);
Create the second activity and
layout
In the app/src/main/java folder, choose
File → New → Activity, and choose the option for Empty Activity.
You will be presented with a new screen where you can choose
options for your new activity.
Check the activity in AndroidManifest.xml
Let say your First activity is sendMessageActivity and your second
activity is receiveMessageActivity
Request code: The request code you set when you launched
the Activity with startActivityForResult()
Result code: the result code set in the launched Activity, usually
one of RESULT_OK or RESULT_CANCELED
Intent data: The intent that contains the data returned from the
launched Activity.
String[] contactsname={};
Cont’d
N.B. For complex layouts or if there is need to customize our list view
or grid view Array Adapter is not suitable rather use custom
adapters.
Custom Array Adapters: ArrayAdapter is an implementation of
BaseAdapter, so if we want more customization then we can create
a custom adapter and extend ArrayAdapter on that class.
For e.g
if we want to create a view something other than a TextView like
displaying an image with text for each item, we extend the
ArrayAdapter class and override getView() to return the type of view
you want for each item.
Simple Cursor Adapter: An easy adapter to map columns from a cursor to
TextViews or ImageViews defined in an XML file. You can specify which columns
you want, which views you want to display the columns, and the XML file that
defines the appearance of these views.
fromcolumns and toviews arrays tells which columns in the cursor to match to which
views
Try This …
Top Level Activity
xml <LinearLayout
android:orientation=“vertical”>
<ImageView
android:layout_width="200dp"
android:layout_height="100dp"
android:src="@drawable/starbuzz_logo"
android:contentDescription="@string/starbuzz_logo" />
<ListView
android:id="@+id/list_options"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:entries="@array/options" />
Strings.xml
<string-array name="options">
<item>Drinks</item>
<item>Food</item>
<item>Stores</item>
Cont’d
Java
//oncreatemethod
AdapterView.OnItemClickListener itemClickListener =
new AdapterView.OnItemClickListener(){
public void onItemClick(AdapterView<?> listView,
View itemView,
int position,
long id) {
if (position == 0) {
Intent intent = new Intent(TopLevelActivity.this,
DrinkCategoryActivity.class);
startActivity(intent);
}
}
};
//Add the listener to the list view
ListView listView = (ListView) findViewById(R.id.list_options);
listView.setOnItemClickListener(itemClickListener);
}
}
Drink Category Activity
Xml
<LinearLayout
android:orientation=“vertical”>
<ListView
android:id="@+id/list_drinks"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
<ImageView
android:id="@+id/photo"
android:layout_width="190dp"
android:layout_height="190dp" />
<TextView
android:id="@+id/name"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:id="@+id/description"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
Cont’d public static final String EXTRA_DRINKID = "drinkId";
int drinkId = (Integer)getIntent().getExtras().get(EXTRA_DRINKID);
Java Drink drink = Drink.drinks[drinkId];
Yes No
Cont’d AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setTitle("Login Alert")
.setMessage("Are you sure, you want to exit ?")
Java Code .setCancelable(false)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
MainActivity.this.finish();
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
//Creating dialog box
AlertDialog dialog = builder.create();
dialog.show();
}
});
Progress Dialog: is used to display the status of work being done like
analyzing status of work or downloading a file.
By default the Progress Bar will be displayed as a Spinning wheel, if
we want to display it in a horizontal bar we have to change the style
property to horizontal like
style="?android:attr/progressBarStyleHorizontal".
Progress bar supports two type of modes to show the progress.
Determinate
Indeterminate
In our Activity
final ProgressBar simpleProgressBar = (ProgressBar) findViewById(R.id.simpleProgressBar);
Button startButton = (Button) findViewById(R.id.startButton);
// perform click event on button
startButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// visible the progress bar
Determinate Mode
progressDialog = new ProgressDialog(MainActivity.this);
progressDialog.setMax(100); // Progress Dialog Max Value
progressDialog.setMessage("Loading..."); // Setting Message
progressDialog.setTitle("ProgressDialog"); // Setting Title
progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); // Progress Dialog Style Horizontal
progressDialog.show(); // Display Progress Dialog
progressDialog.setCancelable(false);
new Thread(new Runnable() {
@Override
public void run() {
try {
while (progressDialog.getProgress() <= progressDialog.getMax()) {
Thread.sleep(200);
progressDialog.incrementProgressBy(2);
if (progressDialog.getProgress() == progressDialog.getMax()) {
progressDialog.dismiss();
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}).start();
}
});
Date and Timer Picker Dialog: A dialog that is used to select date
and time.
Custom Dialog: To create a Custom Dialog we need to create a
Custom Layout for the Dialog window with Layout and Widget
elements.
We set the custom layout as the dialog content view
dialog.setContentView(R.layout.custom_dialog);
dialog.setTitle("Custom Dialog");
we need to mention all activity it in the Fragment is not required to mention in the
manifest.xml file manifest file
<LinearLayout
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="@string/workout_title"
android:id="@+id/textTitle" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/workout_description"
android:id="@+id/textDescription" />
DetailActivity Layout
layout file requires a single view or view group as its root element. If
your activity only contains a fragment, the fragment itself can be
the root element.
<fragment
xmlns:android="http://schemas.android.com/apk/res/android"
android:name="com.hfad.workout.WorkoutDetailFragment“
android:id="@+id/detail_frag"
android:layout_width="match_parent"
android:layout_height="match_parent" />
Workout class public class WorkoutDetailFragment extends F
{
private long workoutId;
(refer page no. 360) @Override
public View onCreateView(LayoutInflater in
Fragments don’t include ViewGroup container,
a findViewById() method, for instance. Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_worko
To get a reference to a fragment’s views, container, false);
we first have to get a reference to the }
@Override
fragment’s root view using the getView() public void onStart() {
super.onStart();
method, and use that to find its child views.
View view = getView();
if (view != null) {
TextView title = (TextView)
view.findViewById(R.id.textTitle);
Workout workout = Workout.workouts[(int) wo
title.setText(workout.getName());
TextView description = (TextView)
view.findViewById(R.id.textDescription
description.setText(workout.getDescriptio
}
WorkList Fragment
A list fragment is a fragment that contains only a list
A list fragment is a type of fragment that specializes in working with
a list view. It has a default layout that contains the list view.
Advantage of List Fragment
You don’t to create your own Layout
There is no XML layout needed. List Fragment define there own
layout programmatically.
getListView() method is used to access the list view in your fragment
code
You don’t have to implement your own event Listener
List Fragment class automatically implements an event listener that
listens for when items in the list view are clicked. We just need to
implement onListItemClick() method.
Add data to ListView Fragment
We want to supply the list view in WorkoutListFragment with an array
of workout names
ArrayAdapter can be used to bind our workout names(array) in list
view.
Unlike an Activity we cant use this to pass the current context to the
array adapter. Why?
The solution is use another object getContext() method to get a
reference to the current context.
If the adapter is created on the fragment’s onCreateView()
method, the getContext() method of the onCreateView()
LayoutInflator parameter can be used to get the context instead.
The last step is to set adapter in the listview. We use setListAdapter()
method.
WorkListFragment
public class WorkoutListFragment extends ListFragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup
container,
Bundle savedInstanceState) {
String[] names = new String[Workout.workouts.length];
for (int i = 0; i < names.length; i++) {
names[i] = Workout.workouts[i].getName();
}
ArrayAdapter<String> adapter = new ArrayAdapter<>(
inflater.getContext(), android.R.layout.simple_list_item_1,
names);
setListAdapter(adapter);
return super.onCreateView(inflater, container, savedInstanceState);
}
}
Main Activity Layout
<fragment
xmlns:android="http://schemas.android.com/apk/res/android"
android:name="com.hfad.workout.WorkoutListFragment“
android:id="@+id/detail_frag"
android:layout_width="match_parent"
android:layout_height="match_parent" />
Connect the list to detail
3 steps
Add code to WorkoutListFragment that waits for a workout to be
clicked.
When that code runs, call some code in MainActivity.java that will
start DetailActivity, passing it the Id of the Workout
Get DetailActivity to pass the ID to WorkoutDetailFragment so that the
fragment can display details of the correct workout.
By defining Interface in our work list fragment we can communicate
the work list with main activity with little effort as well we can reuse
code.
ListView Fragment
Define the Listener interface
static interface Listener {
void itemClicked(long id);
};
Register the listener: We need to save a reference to the activity
WorkoutListFragment.
private Listener listener;
public void onAttach(Context context) {
super.onAttach(context);
this.listener = (Listener)context;
}
Cont’d
Respond to clicks: When an item in WorkoutListFragment gets
clicked, we want to call the listener’s itemClicked() method.
public void onListItemClick(ListView listView, View itemView, int position,
long id) {
if (listener != null) {
listener.itemClicked(id);
}
}
Main Activity
Main Activity needs to implement the interface
public class MainActivity extends AppCompatActivity
implements WorkoutListFragment.Listener {
@Override
public void itemClicked(long id) {
Intent intent = new Intent(this, DetailActivity.class);
intent.putExtra(“id”, (int)id);
startActivity(intent);
}