SlideShare una empresa de Scribd logo
1 de 61
©W3Engineers2018
Android Apps
Development
Md. Moniruzzaman (Monir)
Sr. Software Engineer
06-09-2018
Android apps development
Md. Moniruzzaman (Monir)
Agenda
 Overview of the Android App component(Activities, Services,
Broadcast receivers, Content providers)
 Android Platform Architecture
 Activity
 Fragment
 Intent & Filters
 Context
 Android Layout
Android apps development
Md. Moniruzzaman (Monir)
Agenda
 Toolbar
 Card view
 Navigation Drawer
 Android animation
 Android Resource management
 View pager
 Recycler View
 Adapter
Android apps development
Md. Moniruzzaman (Monir)
Objectives
After attending this session you are expected to be able to
 Create a android project
 Activity/Fragment life cycle knowledge
 UI Design
 Display category-wise/section-wise list of data
 Android animation creation
 Fragment management
Android apps development
Md. Moniruzzaman (Monir)
Android App component
App components are the essential building blocks of an Android app. Each component is an
entry point through which the system or a user can enter your app. Some components
depend on others.
There are four different types of app components:
• Activities.
• Services.
• Broadcast receivers.
• Content providers.
Each type serves a distinct purpose and has a distinct lifecycle that defines how the
component is created and destroyed.
Android apps development
Md. Moniruzzaman (Monir)
Android Platform Architecture
Android is an open source, Linux-based software stack created for a wide array
of devices and form factors. The following diagram shows the major components
of the Android platform.
Android apps development
Md. Moniruzzaman (Monir)
Anatomy of Android Application
Android apps development
Md. Moniruzzaman (Monir)
Anatomy of Android Application
Android apps development
Md. Moniruzzaman (Monir)
Activities
Activities are one of the fundamental building blocks of apps on the Android
platform. Skillfully managing activities allows you to ensure that, for example:
• Orientation changes take place smoothly without disrupting the user
experience.
• User data is not lost during activity transitions.
• The system kills processes when it's appropriate to do so.
Android apps development
Md. Moniruzzaman (Monir)
Activities
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
Android apps development
Md. Moniruzzaman (Monir)
The Activity Lifecycle
As a user navigates through, the Activity instances in your app transition through
different states in their lifecycle. The Activity class provides a number of callbacks
that allow the activity to know that a state has changed.
Activity-lifecycle concepts: To navigate transitions between stages of the
activity lifecycle, the Activity class provides a core set of six
callbacks: onCreate(), onStart(), onResume(), onPause(), onStop(),
and onDestroy().
continue…
Android apps development
Md. Moniruzzaman (Monir)
Activity-lifecycle concepts
Android apps development
Md. Moniruzzaman (Monir)
AndroidManifest.xml
An application can have one or more activities without any restriction. Every
activity you define for your application must be declared in
your AndroidManifest.xml file and the main activity for your app must be
declared in the manifest with an <intent-filter> that includes the MAIN action and
LAUNCHER category .
If either the MAIN action or LAUNCHER category are not declared for one of your
activities, then your app icon will not appear in the Home screen's list of apps.
Android apps development
Md. Moniruzzaman (Monir)
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.tutorialspoint7.myapplication">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher“
android:label="@string/app_name"
android:supportsRtl="true“
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Android apps development
Md. Moniruzzaman (Monir)
Fragments
A Fragment is a piece of an activity which enable more modular activity design.
It will not be wrong if we say, a fragment is a kind of sub-activity.
You create fragments by extending Fragment class and You can insert a
fragment into your activity layout by declaring the fragment in the activity's layout
file, as a <fragment> element.
Android apps development
Md. Moniruzzaman (Monir)
Fragment Life Cycle
Android apps development
Md. Moniruzzaman (Monir)
Adding a Fragment to an Activity
There are two ways you can add a fragment to the activity layout:
• Declare the fragment inside the activity's layout file:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent">
<fragment android:name="com.example.news.ArticleListFragment"
android:id="@+id/list"
android:layout_weight="1"
android:layout_width="0dp"
android:layout_height="match_parent" />
<fragment android:name="com.example.news.ArticleReaderFragment"
android:id="@+id/viewer"
android:layout_weight="2"
android:layout_width="0dp"
android:layout_height="match_parent" />
</LinearLayout>
Android apps development
Md. Moniruzzaman (Monir)
Adding a Fragment to an Activity
● Or, programmatically add the fragment to an existing ViewGroup:
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction =
fragmentManager.beginTransaction();
You can then add a fragment using the add() method, specifying the fragment to add and the view in
which to insert it. For example:
ExampleFragment fragment = new ExampleFragment();
fragmentTransaction.add(R.id.fragment_container, fragment);
fragmentTransaction.commit();
Note: To replace existing fragment : - fragmentTransaction.replace(R.id.fragment_container, fragment);
Android apps development
Md. Moniruzzaman (Monir)
Android-Intents & Filters
An Android Intent is an abstract description of an operation to be performed. It can be used
with startActivity to launch an Activity, broadcastIntent to send it to any interested
BroadcastReceiver components, and startService(Intent) or bindService(Intent,
ServiceConnection, int) to communicate with a background Service.
Types of Intents:
There are following two types of intents supported by Android
Android apps development
Md. Moniruzzaman (Monir)
Intents
● Explicit Intents
// Explicit Intent by specifying its class name
Intent i = new Intent(FirstActivity.this, SecondActivity.class);
// Starts TargetActivity
startActivity(i);
● Implicit Intents
Intent read1=new Intent();
read1.setAction(android.content.Intent.ACTION_VIEW);
read1.setData(ContactsContract.Contacts.CONTENT_URI);
startActivity(read1);
Android apps development
Md. Moniruzzaman (Monir)
Context
You can get the context by invoking getApplicationContext(), getContext(), getBaseContext(), or this(
when in a class that extends from Context, such as the Application, Activity, Service and IntentService
classes)
Typical uses of context:
Creating new objects: Creating new views, adapters, listeners:
TextView tv = new TextView(getContext()); ListAdapter adapter = new
SimpleCursorAdapter(getApplicationContext(), ...);
Accessing components implicitly: Regarding content providers, broadcasts, intent
getApplicationContext().getContentResolver().query(uri, ...);
Android apps development
Md. Moniruzzaman (Monir)
Android Layout
A layout defines the visual structure for a user interface, such as the UI for
an activity or app widget. You can declare a layout in two ways:
• Declare UI elements in XML. Android provides a straightforward XML
vocabulary that corresponds to the View classes and subclasses, such as
those for widgets and layouts.
• Instantiate layout elements at runtime. Your application can create View
and ViewGroup objects (and manipulate their properties) programmatically.
Android apps development
Md. Moniruzzaman (Monir)
Layouts Types
There are different view layouts in an android mobile application. The six different
layouts are:
1. Linear Layout
2. Relative Layout
3. Table Layout
4. Frame Layout
5. Coordinator Layout
6. Constraint Layout
Android apps development
Md. Moniruzzaman (Monir)
Layout Attributes
● android:id -- This is the ID which uniquely identifies the view.
● android:layout_width -- This is the width of the layout.
● android:layout_height -- This is the height of the layout
● android:layout_marginTop --This is the extra space on the top side of the
layout.
● android:layout_marginBottom --This is the extra space on the bottom side
of the layout.
● android:layout_marginLeft --This is the extra space on the left side of the
layout.
● android:layout_marginRight -- This is the extra space on the right side of
the layout.
Android apps development
Md. Moniruzzaman (Monir)
Layout Attributes
● android:layout_gravity --This specifies how child Views are positioned.
● android:layout_weight -- This specifies how much of the extra space in the
layout should be allocated to the View
● android:layout_x -- This specifies the x-coordinate of the layout.
● android:layout_y --This specifies the y-coordinate of the layout.
● android:paddingLeft --This is the left padding filled for the layout.
● android:paddingRight --This is the right padding filled for the layout.
● android:paddingTop -- This is the top padding filled for the layout.
● android:paddingBottom -- This is the bottom padding filled for the layout.
Android apps development
Md. Moniruzzaman (Monir)
Layout Attributes
You can specify width and height with exact measurements like dp (Density-
independent Pixels), sp ( Scale-independent Pixels), pt ( Points which is 1/72 of
an inch), px( Pixels), mm ( Millimeters) and finally in (inches).) but more often,
you will use one of these constants to set the width or height −
● android:layout_width=wrap_content tells your view to size itself to the
dimensions required by its content.
● android:layout_width=fill_parent tells your view to become as big as its
parent view.
Android apps development
Md. Moniruzzaman (Monir)
ConstraintLayout
To use ConstraintLayout in your project, proceed as follows:
Ensure you have the maven.google.com repository declared in your module-levelbuild.gradle file:
repositories {
maven {
url 'https://maven.google.com'
}
}
Add the library as a dependency in the same build.gradle file:
dependencies {
compile 'com.android.support.constraint:constraint-layout:1.0.2'
}
In the toolbar or sync notification, click Sync Project with Gradle Files.
Now you're ready to build your layout with ConstraintLayout.
Android apps development
Md. Moniruzzaman (Monir)
ConstraintLayout
Figure : The Attributes window includes controls for 1 size ratio, 2 delete
constraint, 3 height/width mode, 4margins, and 5 constraint bias.
Android apps development
Md. Moniruzzaman (Monir)
Toolbar
<resources>
<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
<!-- Customize your theme here. -->
<item name="colorPrimary">@color/colorPrimary</item>
<item name="colorPrimaryDark">@color/colorPrimaryDark</item>
<item name="colorAccent">@color/colorAccent</item>
</style>
</resources>
<android.support.v7.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:background="@color/colorPrimary" />
Android apps development
Md. Moniruzzaman (Monir)
Toolbar
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//getting the toolbar
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
//setting the title
toolbar.setTitle("My Toolbar");
//placing toolbar in place of actionbar
setSupportActionBar(toolbar);
}
Android apps development
Md. Moniruzzaman (Monir)
Setting up a Menu on the Toolbar
Creating a Menu:
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:id="@+id/menuAbout"
android:title="About" />
<item
android:id="@+id/menuSettings"
android:title="Settings" />
<item
android:id="@+id/menuLogout"
android:title="Logout" />
</menu>
Android apps development
Md. Moniruzzaman (Monir)
Setting up a Menu on the Toolbar
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.menu, menu);
return true;
}
Android apps development
Md. Moniruzzaman (Monir)
Handling Menu Clicks
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch(item.getItemId()){
case R.id.menuAbout:
Toast.makeText(this, "You clicked about", Toast.LENGTH_SHORT).show();
break;
case R.id.menuSettings:
Toast.makeText(this, "You clicked settings", Toast.LENGTH_SHORT).show();
break;
case R.id.menuLogout:
Toast.makeText(this, "You clicked logout", Toast.LENGTH_SHORT).show();
break;
}
return true;
}
Android apps development
Md. Moniruzzaman (Monir)
Navigation Drawer
● The navigation drawer is a UI panel that shows your app's main navigation
menu. It is hidden when not in use, but appears when the user swipes a
finger from the left edge of the screen:
Android apps development
Md. Moniruzzaman (Monir)
Add a drawer to into layout
<?xml version="1.0" encoding="utf-8"?>
<!-- Use DrawerLayout as root container for activity -->
<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true">
<!-- Layout to contain contents of main body of screen (drawer will slide over this) -->
<FrameLayout
android:id="@+id/content_frame"
android:layout_width="match_parent"
android:layout_height="match_parent" />
Android apps development
Md. Moniruzzaman (Monir)
Add a drawer to into layout
<!-- Container for contents of drawer - use NavigationView to make configuration easier -->
<android.support.design.widget.NavigationView
android:id="@+id/nav_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
android:fitsSystemWindows="true“
app:menu="@menu/drawer_view"
app:headerLayout="@layout/nav_header" />
</android.support.v4.widget.DrawerLayout>
Android apps development
Md. Moniruzzaman (Monir)
Create the menu resource
Create the menu resource with the corresponding file name. For example, at res/menu/drawer_view.xml:
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android" >
<group android:checkableBehavior="single">
<item
android:id="@+id/nav_camera"
android:icon="@drawable/ic_menu_camera"
android:title="@string/import" />
<item
android:id="@+id/nav_gallery"
android:icon="@drawable/ic_menu_gallery"
android:title="@string/gallery" />
<item
android:id="@+id/nav_slideshow"
android:icon="@drawable/ic_menu_slideshow"
android:title="@string/slideshow" />
<item
android:id="@+id/nav_manage"
android:icon="@drawable/ic_menu_manage"
android:title="@string/tools" />
</group>
</menu>
Android apps development
Md. Moniruzzaman (Monir)
Handle navigation click events
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mDrawerLayout = findViewById(R.id.drawer_layout);
NavigationView navigationView = findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(
new NavigationView.OnNavigationItemSelectedListener() {
@Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
// set item as selected to persist highlight
menuItem.setChecked(true);
// close drawer when item is tapped
mDrawerLayout.closeDrawers();
// Add code here to update the UI based on the item selected
// For example, swap UI fragments here
return true;
}
});
}
Android apps development
Md. Moniruzzaman (Monir)
Android animation
● Adding animations to your app interface will give high quality feel to your android
applications. Animations can be performed through either XML or android code.
● There are 3 types of Animations:
● Property Animations — They are used to alter property of objects (Views or non view
objects).
● View Animations — They are used to do simple animations like changing size,
position, rotation, control transparency.
● Drawable Animations —This is used to do animation using drawables. An XML file
specifying various list of drawables is made which are run one by one just like a roll of a
film. This is not much used so I won’t cover it.
Android apps development
Md. Moniruzzaman (Monir)
Android Animation Using XML
Create an xml file which defines type of animation to perform. This file should be
located under anim folder under res directory (res ⇒ anim ⇒ animation.xml). If
you don’t have anim folder in your res directory create one. Following is example
of simple fade in animation.
Android apps development
Md. Moniruzzaman (Monir)
Android Animation Using XML
● Create xml that defines the animation: fade_in.xml
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
android:fillAfter="true" >
<alpha
android:duration="1000"
android:fromAlpha="0.0"
android:interpolator="@android:anim/accelerate_interpolator"
android:toAlpha="1.0" />
</set>
Android apps development
Md. Moniruzzaman (Monir)
Loading Animation
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_fadein);
txtMessage = (TextView) findViewById(R.id.txtMessage);
// load the animation
Animation animFadein =
AnimationUtils.loadAnimation(getApplicationContext(),
R.anim.fade_in);
}
Android apps development
Md. Moniruzzaman (Monir)
Animation state listeners
public class FadeInActivity extends Activity implements AnimationListener {
animFadein.setAnimationListener(this);
@Override
public void onAnimationEnd(Animation animation) {
// Take any action after completing the animation
}
@Override
public void onAnimationRepeat(Animation animation) {
// Animation is repeating
}
@Override
public void onAnimationStart(Animation animation) {
// Animation started
}
}
Android apps development
Md. Moniruzzaman (Monir)
Start the animation
You can start animation whenever you want by calling startAnimation on any UI element by passing the
type of animation. In this example i am calling fade in animation on TextView:
// start the animation
txtMessage.startAnimation(animFadein);
However instead of xml we can also use android code to create animation such like a class is
ObjectAnimator
ObjectAnimator rotationAnimator =
ObjectAnimator.ofFloat(animateTextView, "rotation", 360f);
rotationAnimator.setDuration(2000);
Android apps development
Md. Moniruzzaman (Monir)
Creating Lists and Cards
To create complex lists and cards with material design styles in your apps, you can use
the RecyclerView and CardView widgets.
Figure : The RecyclerView widget.
RecyclerView provides these built-in layout managers:
LinearLayoutManager shows items in a vertical or horizontal scrolling list.
GridLayoutManager shows items in a grid.
StaggeredGridLayoutManager shows items in a staggered grid.
To create a custom layout manager, extend
the RecyclerView.LayoutManager class.
Android apps development
Md. Moniruzzaman (Monir)
RecyclerView
<!-- A RecyclerView with some commonly used attributes -->
<android.support.v7.widget.RecyclerView
android:id="@+id/my_recycler_view"
android:scrollbars="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
Once you have added a RecyclerView widget to your layout, obtain a handle to
the object, connect it to a layout manager, and attach an adapter for the data to
be displayed:
Android apps development
Md. Moniruzzaman (Monir)
RecyclerView
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.my_activity);
mRecyclerView = (RecyclerView) findViewById(R.id.my_recycler_view);
// use this setting to improve performance if you know that changes
// in content do not change the layout size of the RecyclerView
mRecyclerView.setHasFixedSize(true);
// use a linear layout manager
mLayoutManager = new LinearLayoutManager(this);
mRecyclerView.setLayoutManager(mLayoutManager);
// specify an adapter (see also next example)
mAdapter = new MyAdapter(myDataset);
mRecyclerView.setAdapter(mAdapter);
}
Android apps development
Md. Moniruzzaman (Monir)
Adapter
The adapter provides access to the items in your data set, creates views for items, and replaces the content of some of the
views with new data items when the original item is no longer visible.
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> {
private String[] mDataset;
// Provide a reference to the views for each data item
// Complex data items may need more than one view per item, and
// you provide access to all the views for a data item in a view holder
public static class ViewHolder extends RecyclerView.ViewHolder {
// each data item is just a string in this case
public TextView mTextView;
public ViewHolder(TextView v) {
super(v);
mTextView = v;
}
}
Android apps development
Md. Moniruzzaman (Monir)
Adapter
// Provide a suitable constructor (depends on the kind of dataset)
public MyAdapter(String[] myDataset) {
mDataset = myDataset;
}
// Create new views (invoked by the layout manager)
@Override
public MyAdapter.ViewHolder onCreateViewHolder(ViewGroup parent,
int viewType) {
// create a new view
TextView v = (TextView) LayoutInflater.from(parent.getContext())
.inflate(R.layout.my_text_view, parent, false);
// set the view's size, margins, paddings and layout parameters
ViewHolder vh = new ViewHolder(v);
return vh;
}
Android apps development
Md. Moniruzzaman (Monir)
Adapter
// Replace the contents of a view (invoked by the layout manager)
@Override
public void onBindViewHolder(ViewHolder holder, int position) {
// - get element from your dataset at this position
// - replace the contents of the view with that element
holder.mTextView.setText(mDataset[position]);
}
// Return the size of your dataset (invoked by the layout manager)
@Override
public int getItemCount() {
return mDataset.length;
}
}
Android apps development
Md. Moniruzzaman (Monir)
Different view in adapter
To handle the case where you want different types of view for different rows. For instance,
in a contacts application you may want even rows to have pictures on the left side and odd
rows to have pictures on the right. In that case, you would use:
@Override
public int getViewTypeCount() {
return 2;
}
@Override
public int getItemViewType(int position) {
return position % 2;
}
Android apps development
Md. Moniruzzaman (Monir)
Different view in adapter
@Override
public MainVH onCreateViewHolder(ViewGroup parent, int viewType) {
int layoutRes;
switch (viewType) {
case VIEW_TYPE_HEADER:
layoutRes = R.layout.item_header;
break;
case VIEW_TYPE_FOOTER:
layoutRes = R.layout.item_footer;
break;
default:
layoutRes = R.layout.content_swipe;
break;
}
View v = LayoutInflater.from(parent.getContext())
.inflate(layoutRes, parent, false);
return new MainVH(v);
}
Android apps development
Md. Moniruzzaman (Monir)
Create Cards
CardView extends the FrameLayout class and lets you show information inside cards that have a consistent look across the
platform. CardView widgets can have shadows and rounded corners.
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:card_view="http://schemas.android.com/apk/res-auto"
... >
<!-- A CardView that contains a TextView -->
<android.support.v7.widget.CardView
xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:id="@+id/card_view"
android:layout_gravity="center"
android:layout_width="200dp"
android:layout_height="200dp"
card_view:cardCornerRadius="4dp">
<TextView
android:id="@+id/info_text"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</android.support.v7.widget.CardView>
</LinearLayout>
Android apps development
Md. Moniruzzaman (Monir)
Add Dependencies
The RecyclerView and CardView widgets are part of the v7 Support Libraries. To
use these widgets in your project, add these Gradle dependencies to your app's
module:
dependencies {
compile 'com.android.support:cardview-v7:21.0.+'
compile 'com.android.support:recyclerview-v7:21.0.+‘
}
Android apps development
Md. Moniruzzaman (Monir)
Android ViewPager
Android ViewPager widget is found in the support library and it allows the user to swipe left or right to
see an entirely new screen.
<android.support.v4.view.ViewPager
android:id="@+id/viewpager"
android:layout_width="match_parent"
android:layout_height="match_parent“/>
@Override protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ViewPager viewPager = (ViewPager) findViewById(R.id.viewpager);
viewPager.setAdapter(new CustomPagerAdapter(this));
}
Android apps development
Md. Moniruzzaman (Monir)
PagerAdapter
public class CustomPagerAdapter extends PagerAdapter {
private Context mContext;
public CustomPagerAdapter(Context context) {
mContext = context;
}
@Override public Object instantiateItem(ViewGroup collection, int
position) {
ModelObject modelObject = ModelObject.values()[position];
LayoutInflater inflater = LayoutInflater.from(mContext);
ViewGroup layout = (ViewGroup)
inflater.inflate(modelObject.getLayoutResId(), collection, false);
collection.addView(layout); return layout;
}
Android apps development
Md. Moniruzzaman (Monir)
PagerAdapter
@Override
public void destroyItem(ViewGroup collection, int position, Object view) {
collection.removeView((View) view);
}
@Override
public int getCount() { return ModelObject.values().length; }
@Override
public boolean isViewFromObject(View view, Object object) {
return view == object; }
@Override
public CharSequence getPageTitle(int position) {
ModelObject customPagerEnum = ModelObject.values()[position];
return mContext.getString(customPagerEnum.getTitleResId());
}
Android apps development
Md. Moniruzzaman (Monir)
PagerAdapter
● CustomPagerAdapter(Context context) : The constructor needs a Context reference. The context is saved as
a member variable of the class since it’s used later to access the individual page layouts from the enum class
● instantiateItem : In this case, we use the enum and inflate the particular enum value’s associated layout. Then,
we add the newly inflated layout to the ViewGroup(collection of Views) maintained by the PagerAdapter, and
then we return that layout. The object being returned by this method is also used later on, as the second
parameter in the isViewFromObject method
● destroyItem : This method removes a particular view from the ViewGroup maintained by the PagerAdapter
● getCount : It simply returns the number of views that will be maintained by the ViewPager. For this example,
the count is the number of enum values in the model object
● isViewFromObject : This method checks whether a particular object belongs to a given position, which is
made simple. As noted earlier, the second parameter is of type Object and is the same as the return value from
the instantiateItem method
● getPageTitle : At a given position, we need to supply the PagerAdapter with a title. This usually manifests itself
in the ActionBar as the Activity’s title, or sometimes tabs will hook into this method for labelling each tab. In this
case we’ve kept it for labelling only
Android apps development
Md. Moniruzzaman (Monir)
Assignment Details
Create a Application which have a navigation drawer with two tab option (Home and Food).
1. Home: User can see all order list he/she has already done.
2. Food: User can order any food item from list of category item including every item have a
multiple image showing option by swiping
Note: i) All the item design and layout design will be using only constraint layout and co-
ordinator layout. ii) Home and Food tab will be fragment. Basic features should be same what I
draw on the white board.
(Duration 4 days including today)
Android apps development
Md. Moniruzzaman (Monir)
Assignment Guidelines
 (There will be toolbar , list of data will be shown using
recyclerview cardview and adapter )
 For showing multiple image there will be used viewpager,
adapter
 Data list could be static.
 For any help conduct with me or any android developer
Android apps development
Md. Moniruzzaman (Monir)
Resources
• https://developer.android.com/guide/components/fundamentals.html#Components
• https://developer.android.com/guide/platform/index.html
• https://developer.android.com/guide/components/activities/activity-lifecycle.html
• https://developer.android.com/guide/components/fragments.html
• https://developer.android.com/training/basics/fragments/creating.html
• https://developer.android.com/guide/topics/ui/declaring-layout.html
• https://developer.android.com/training/basics/fragments/fragment-ui.html
• https://developer.android.com/guide/topics/resources/providing-
resources.html#ResourceTypes
• https://www.androidhive.info/2013/06/android-working-with-xml-animations/
• https://medium.com/mindorks/a-beginners-guide-to-implement-android-animations-part-1-2-
part-series-b5fce1fc85
• https://developer.android.com/training/material/lists-cards.html#RecyclerView
• https://developer.android.com/training/constraint-layout/
• https://www.tutorialspoint.com/android/index.htm

Más contenido relacionado

La actualidad más candente

La actualidad más candente (20)

Introduction to Android
Introduction to Android Introduction to Android
Introduction to Android
 
Introduction to Android - Mobile Portland
Introduction to Android - Mobile PortlandIntroduction to Android - Mobile Portland
Introduction to Android - Mobile Portland
 
Android Web app
Android Web app Android Web app
Android Web app
 
Android Overview
Android OverviewAndroid Overview
Android Overview
 
Android overview
Android overviewAndroid overview
Android overview
 
Android Application Development Using Java
Android Application Development Using JavaAndroid Application Development Using Java
Android Application Development Using Java
 
PPT Companion to Android
PPT Companion to AndroidPPT Companion to Android
PPT Companion to Android
 
All about Android app development -Texavi presentation
All about Android app development -Texavi presentationAll about Android app development -Texavi presentation
All about Android app development -Texavi presentation
 
Android ppt
Android pptAndroid ppt
Android ppt
 
Introduction to Android Environment
Introduction to Android EnvironmentIntroduction to Android Environment
Introduction to Android Environment
 
Introduction to Android Development
Introduction to Android DevelopmentIntroduction to Android Development
Introduction to Android Development
 
Android tutorial
Android tutorialAndroid tutorial
Android tutorial
 
What's new in Android Pie
What's new in Android PieWhat's new in Android Pie
What's new in Android Pie
 
Android ppt
Android pptAndroid ppt
Android ppt
 
Mobile appliaction w android week 1 by osama
Mobile appliaction w android week 1 by osamaMobile appliaction w android week 1 by osama
Mobile appliaction w android week 1 by osama
 
Custom Android App Development – Web Animation India
Custom Android App Development – Web Animation IndiaCustom Android App Development – Web Animation India
Custom Android App Development – Web Animation India
 
Android tutorial points
Android tutorial pointsAndroid tutorial points
Android tutorial points
 
Android app development ppt
Android app development pptAndroid app development ppt
Android app development ppt
 
Android Platform Architecture
Android Platform ArchitectureAndroid Platform Architecture
Android Platform Architecture
 
Android Programming Seminar
Android Programming SeminarAndroid Programming Seminar
Android Programming Seminar
 

Similar a Android Apps Development Basic

android layouts
android layoutsandroid layouts
android layouts
Deepa Rani
 
Mobile Application Development Lecture 05 & 06.pdf
Mobile Application Development Lecture 05 & 06.pdfMobile Application Development Lecture 05 & 06.pdf
Mobile Application Development Lecture 05 & 06.pdf
AbdullahMunir32
 

Similar a Android Apps Development Basic (20)

Android apps development
Android apps developmentAndroid apps development
Android apps development
 
Native Android Development Practices
Native Android Development PracticesNative Android Development Practices
Native Android Development Practices
 
Beginning Native Android Apps
Beginning Native Android AppsBeginning Native Android Apps
Beginning Native Android Apps
 
Android Introduction
Android IntroductionAndroid Introduction
Android Introduction
 
Lecture #1 Creating your first android project
Lecture #1  Creating your first android projectLecture #1  Creating your first android project
Lecture #1 Creating your first android project
 
Notes Unit3.pptx
Notes Unit3.pptxNotes Unit3.pptx
Notes Unit3.pptx
 
Android session 2
Android session 2Android session 2
Android session 2
 
mobile application development -unit-3-
mobile application development  -unit-3-mobile application development  -unit-3-
mobile application development -unit-3-
 
Fragments: Why, How, What For?
Fragments: Why, How, What For?Fragments: Why, How, What For?
Fragments: Why, How, What For?
 
android layouts
android layoutsandroid layouts
android layouts
 
Android training day 2
Android training day 2Android training day 2
Android training day 2
 
Mobile application development
Mobile application developmentMobile application development
Mobile application development
 
Hello android world
Hello android worldHello android world
Hello android world
 
Introduction to Android Programming
Introduction to Android ProgrammingIntroduction to Android Programming
Introduction to Android Programming
 
Android Development : (Android Studio, PHP, XML, MySQL)
Android Development : (Android Studio, PHP, XML, MySQL)Android Development : (Android Studio, PHP, XML, MySQL)
Android Development : (Android Studio, PHP, XML, MySQL)
 
Android application development for TresmaxAsia
Android application development for TresmaxAsiaAndroid application development for TresmaxAsia
Android application development for TresmaxAsia
 
Mobile Application Development Lecture 05 & 06.pdf
Mobile Application Development Lecture 05 & 06.pdfMobile Application Development Lecture 05 & 06.pdf
Mobile Application Development Lecture 05 & 06.pdf
 
Hierarchy viewer
Hierarchy viewerHierarchy viewer
Hierarchy viewer
 
ACADGILD:: ANDROID LESSON-How to analyze &amp; manage memory on android like ...
ACADGILD:: ANDROID LESSON-How to analyze &amp; manage memory on android like ...ACADGILD:: ANDROID LESSON-How to analyze &amp; manage memory on android like ...
ACADGILD:: ANDROID LESSON-How to analyze &amp; manage memory on android like ...
 
Android Components & Manifest
Android Components & ManifestAndroid Components & Manifest
Android Components & Manifest
 

Último

Último (20)

IoT Analytics Company Presentation May 2024
IoT Analytics Company Presentation May 2024IoT Analytics Company Presentation May 2024
IoT Analytics Company Presentation May 2024
 
AI presentation and introduction - Retrieval Augmented Generation RAG 101
AI presentation and introduction - Retrieval Augmented Generation RAG 101AI presentation and introduction - Retrieval Augmented Generation RAG 101
AI presentation and introduction - Retrieval Augmented Generation RAG 101
 
Where to Learn More About FDO _ Richard at FIDO Alliance.pdf
Where to Learn More About FDO _ Richard at FIDO Alliance.pdfWhere to Learn More About FDO _ Richard at FIDO Alliance.pdf
Where to Learn More About FDO _ Richard at FIDO Alliance.pdf
 
Designing for Hardware Accessibility at Comcast
Designing for Hardware Accessibility at ComcastDesigning for Hardware Accessibility at Comcast
Designing for Hardware Accessibility at Comcast
 
Measures in SQL (a talk at SF Distributed Systems meetup, 2024-05-22)
Measures in SQL (a talk at SF Distributed Systems meetup, 2024-05-22)Measures in SQL (a talk at SF Distributed Systems meetup, 2024-05-22)
Measures in SQL (a talk at SF Distributed Systems meetup, 2024-05-22)
 
Strategic AI Integration in Engineering Teams
Strategic AI Integration in Engineering TeamsStrategic AI Integration in Engineering Teams
Strategic AI Integration in Engineering Teams
 
Syngulon - Selection technology May 2024.pdf
Syngulon - Selection technology May 2024.pdfSyngulon - Selection technology May 2024.pdf
Syngulon - Selection technology May 2024.pdf
 
AI revolution and Salesforce, Jiří Karpíšek
AI revolution and Salesforce, Jiří KarpíšekAI revolution and Salesforce, Jiří Karpíšek
AI revolution and Salesforce, Jiří Karpíšek
 
THE BEST IPTV in GERMANY for 2024: IPTVreel
THE BEST IPTV in  GERMANY for 2024: IPTVreelTHE BEST IPTV in  GERMANY for 2024: IPTVreel
THE BEST IPTV in GERMANY for 2024: IPTVreel
 
ASRock Industrial FDO Solutions in Action for Industrial Edge AI _ Kenny at A...
ASRock Industrial FDO Solutions in Action for Industrial Edge AI _ Kenny at A...ASRock Industrial FDO Solutions in Action for Industrial Edge AI _ Kenny at A...
ASRock Industrial FDO Solutions in Action for Industrial Edge AI _ Kenny at A...
 
WebAssembly is Key to Better LLM Performance
WebAssembly is Key to Better LLM PerformanceWebAssembly is Key to Better LLM Performance
WebAssembly is Key to Better LLM Performance
 
Integrating Telephony Systems with Salesforce: Insights and Considerations, B...
Integrating Telephony Systems with Salesforce: Insights and Considerations, B...Integrating Telephony Systems with Salesforce: Insights and Considerations, B...
Integrating Telephony Systems with Salesforce: Insights and Considerations, B...
 
ECS 2024 Teams Premium - Pretty Secure
ECS 2024   Teams Premium - Pretty SecureECS 2024   Teams Premium - Pretty Secure
ECS 2024 Teams Premium - Pretty Secure
 
The UX of Automation by AJ King, Senior UX Researcher, Ocado
The UX of Automation by AJ King, Senior UX Researcher, OcadoThe UX of Automation by AJ King, Senior UX Researcher, Ocado
The UX of Automation by AJ King, Senior UX Researcher, Ocado
 
Demystifying gRPC in .Net by John Staveley
Demystifying gRPC in .Net by John StaveleyDemystifying gRPC in .Net by John Staveley
Demystifying gRPC in .Net by John Staveley
 
SOQL 201 for Admins & Developers: Slice & Dice Your Org’s Data With Aggregate...
SOQL 201 for Admins & Developers: Slice & Dice Your Org’s Data With Aggregate...SOQL 201 for Admins & Developers: Slice & Dice Your Org’s Data With Aggregate...
SOQL 201 for Admins & Developers: Slice & Dice Your Org’s Data With Aggregate...
 
Simplified FDO Manufacturing Flow with TPMs _ Liam at Infineon.pdf
Simplified FDO Manufacturing Flow with TPMs _ Liam at Infineon.pdfSimplified FDO Manufacturing Flow with TPMs _ Liam at Infineon.pdf
Simplified FDO Manufacturing Flow with TPMs _ Liam at Infineon.pdf
 
Salesforce Adoption – Metrics, Methods, and Motivation, Antone Kom
Salesforce Adoption – Metrics, Methods, and Motivation, Antone KomSalesforce Adoption – Metrics, Methods, and Motivation, Antone Kom
Salesforce Adoption – Metrics, Methods, and Motivation, Antone Kom
 
Custom Approval Process: A New Perspective, Pavel Hrbacek & Anindya Halder
Custom Approval Process: A New Perspective, Pavel Hrbacek & Anindya HalderCustom Approval Process: A New Perspective, Pavel Hrbacek & Anindya Halder
Custom Approval Process: A New Perspective, Pavel Hrbacek & Anindya Halder
 
Powerful Start- the Key to Project Success, Barbara Laskowska
Powerful Start- the Key to Project Success, Barbara LaskowskaPowerful Start- the Key to Project Success, Barbara Laskowska
Powerful Start- the Key to Project Success, Barbara Laskowska
 

Android Apps Development Basic

  • 1. ©W3Engineers2018 Android Apps Development Md. Moniruzzaman (Monir) Sr. Software Engineer 06-09-2018
  • 2. Android apps development Md. Moniruzzaman (Monir) Agenda  Overview of the Android App component(Activities, Services, Broadcast receivers, Content providers)  Android Platform Architecture  Activity  Fragment  Intent & Filters  Context  Android Layout
  • 3. Android apps development Md. Moniruzzaman (Monir) Agenda  Toolbar  Card view  Navigation Drawer  Android animation  Android Resource management  View pager  Recycler View  Adapter
  • 4. Android apps development Md. Moniruzzaman (Monir) Objectives After attending this session you are expected to be able to  Create a android project  Activity/Fragment life cycle knowledge  UI Design  Display category-wise/section-wise list of data  Android animation creation  Fragment management
  • 5. Android apps development Md. Moniruzzaman (Monir) Android App component App components are the essential building blocks of an Android app. Each component is an entry point through which the system or a user can enter your app. Some components depend on others. There are four different types of app components: • Activities. • Services. • Broadcast receivers. • Content providers. Each type serves a distinct purpose and has a distinct lifecycle that defines how the component is created and destroyed.
  • 6. Android apps development Md. Moniruzzaman (Monir) Android Platform Architecture Android is an open source, Linux-based software stack created for a wide array of devices and form factors. The following diagram shows the major components of the Android platform.
  • 7. Android apps development Md. Moniruzzaman (Monir) Anatomy of Android Application
  • 8. Android apps development Md. Moniruzzaman (Monir) Anatomy of Android Application
  • 9. Android apps development Md. Moniruzzaman (Monir) Activities Activities are one of the fundamental building blocks of apps on the Android platform. Skillfully managing activities allows you to ensure that, for example: • Orientation changes take place smoothly without disrupting the user experience. • User data is not lost during activity transitions. • The system kills processes when it's appropriate to do so.
  • 10. Android apps development Md. Moniruzzaman (Monir) Activities public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } }
  • 11. Android apps development Md. Moniruzzaman (Monir) The Activity Lifecycle As a user navigates through, the Activity instances in your app transition through different states in their lifecycle. The Activity class provides a number of callbacks that allow the activity to know that a state has changed. Activity-lifecycle concepts: To navigate transitions between stages of the activity lifecycle, the Activity class provides a core set of six callbacks: onCreate(), onStart(), onResume(), onPause(), onStop(), and onDestroy(). continue…
  • 12. Android apps development Md. Moniruzzaman (Monir) Activity-lifecycle concepts
  • 13. Android apps development Md. Moniruzzaman (Monir) AndroidManifest.xml An application can have one or more activities without any restriction. Every activity you define for your application must be declared in your AndroidManifest.xml file and the main activity for your app must be declared in the manifest with an <intent-filter> that includes the MAIN action and LAUNCHER category . If either the MAIN action or LAUNCHER category are not declared for one of your activities, then your app icon will not appear in the Home screen's list of apps.
  • 14. Android apps development Md. Moniruzzaman (Monir) AndroidManifest.xml <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.tutorialspoint7.myapplication"> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher“ android:label="@string/app_name" android:supportsRtl="true“ android:theme="@style/AppTheme"> <activity android:name=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest>
  • 15. Android apps development Md. Moniruzzaman (Monir) Fragments A Fragment is a piece of an activity which enable more modular activity design. It will not be wrong if we say, a fragment is a kind of sub-activity. You create fragments by extending Fragment class and You can insert a fragment into your activity layout by declaring the fragment in the activity's layout file, as a <fragment> element.
  • 16. Android apps development Md. Moniruzzaman (Monir) Fragment Life Cycle
  • 17. Android apps development Md. Moniruzzaman (Monir) Adding a Fragment to an Activity There are two ways you can add a fragment to the activity layout: • Declare the fragment inside the activity's layout file: <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="horizontal" android:layout_width="match_parent" android:layout_height="match_parent"> <fragment android:name="com.example.news.ArticleListFragment" android:id="@+id/list" android:layout_weight="1" android:layout_width="0dp" android:layout_height="match_parent" /> <fragment android:name="com.example.news.ArticleReaderFragment" android:id="@+id/viewer" android:layout_weight="2" android:layout_width="0dp" android:layout_height="match_parent" /> </LinearLayout>
  • 18. Android apps development Md. Moniruzzaman (Monir) Adding a Fragment to an Activity ● Or, programmatically add the fragment to an existing ViewGroup: FragmentManager fragmentManager = getSupportFragmentManager(); FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction(); You can then add a fragment using the add() method, specifying the fragment to add and the view in which to insert it. For example: ExampleFragment fragment = new ExampleFragment(); fragmentTransaction.add(R.id.fragment_container, fragment); fragmentTransaction.commit(); Note: To replace existing fragment : - fragmentTransaction.replace(R.id.fragment_container, fragment);
  • 19. Android apps development Md. Moniruzzaman (Monir) Android-Intents & Filters An Android Intent is an abstract description of an operation to be performed. It can be used with startActivity to launch an Activity, broadcastIntent to send it to any interested BroadcastReceiver components, and startService(Intent) or bindService(Intent, ServiceConnection, int) to communicate with a background Service. Types of Intents: There are following two types of intents supported by Android
  • 20. Android apps development Md. Moniruzzaman (Monir) Intents ● Explicit Intents // Explicit Intent by specifying its class name Intent i = new Intent(FirstActivity.this, SecondActivity.class); // Starts TargetActivity startActivity(i); ● Implicit Intents Intent read1=new Intent(); read1.setAction(android.content.Intent.ACTION_VIEW); read1.setData(ContactsContract.Contacts.CONTENT_URI); startActivity(read1);
  • 21. Android apps development Md. Moniruzzaman (Monir) Context You can get the context by invoking getApplicationContext(), getContext(), getBaseContext(), or this( when in a class that extends from Context, such as the Application, Activity, Service and IntentService classes) Typical uses of context: Creating new objects: Creating new views, adapters, listeners: TextView tv = new TextView(getContext()); ListAdapter adapter = new SimpleCursorAdapter(getApplicationContext(), ...); Accessing components implicitly: Regarding content providers, broadcasts, intent getApplicationContext().getContentResolver().query(uri, ...);
  • 22. Android apps development Md. Moniruzzaman (Monir) Android Layout A layout defines the visual structure for a user interface, such as the UI for an activity or app widget. You can declare a layout in two ways: • Declare UI elements in XML. Android provides a straightforward XML vocabulary that corresponds to the View classes and subclasses, such as those for widgets and layouts. • Instantiate layout elements at runtime. Your application can create View and ViewGroup objects (and manipulate their properties) programmatically.
  • 23. Android apps development Md. Moniruzzaman (Monir) Layouts Types There are different view layouts in an android mobile application. The six different layouts are: 1. Linear Layout 2. Relative Layout 3. Table Layout 4. Frame Layout 5. Coordinator Layout 6. Constraint Layout
  • 24. Android apps development Md. Moniruzzaman (Monir) Layout Attributes ● android:id -- This is the ID which uniquely identifies the view. ● android:layout_width -- This is the width of the layout. ● android:layout_height -- This is the height of the layout ● android:layout_marginTop --This is the extra space on the top side of the layout. ● android:layout_marginBottom --This is the extra space on the bottom side of the layout. ● android:layout_marginLeft --This is the extra space on the left side of the layout. ● android:layout_marginRight -- This is the extra space on the right side of the layout.
  • 25. Android apps development Md. Moniruzzaman (Monir) Layout Attributes ● android:layout_gravity --This specifies how child Views are positioned. ● android:layout_weight -- This specifies how much of the extra space in the layout should be allocated to the View ● android:layout_x -- This specifies the x-coordinate of the layout. ● android:layout_y --This specifies the y-coordinate of the layout. ● android:paddingLeft --This is the left padding filled for the layout. ● android:paddingRight --This is the right padding filled for the layout. ● android:paddingTop -- This is the top padding filled for the layout. ● android:paddingBottom -- This is the bottom padding filled for the layout.
  • 26. Android apps development Md. Moniruzzaman (Monir) Layout Attributes You can specify width and height with exact measurements like dp (Density- independent Pixels), sp ( Scale-independent Pixels), pt ( Points which is 1/72 of an inch), px( Pixels), mm ( Millimeters) and finally in (inches).) but more often, you will use one of these constants to set the width or height − ● android:layout_width=wrap_content tells your view to size itself to the dimensions required by its content. ● android:layout_width=fill_parent tells your view to become as big as its parent view.
  • 27. Android apps development Md. Moniruzzaman (Monir) ConstraintLayout To use ConstraintLayout in your project, proceed as follows: Ensure you have the maven.google.com repository declared in your module-levelbuild.gradle file: repositories { maven { url 'https://maven.google.com' } } Add the library as a dependency in the same build.gradle file: dependencies { compile 'com.android.support.constraint:constraint-layout:1.0.2' } In the toolbar or sync notification, click Sync Project with Gradle Files. Now you're ready to build your layout with ConstraintLayout.
  • 28. Android apps development Md. Moniruzzaman (Monir) ConstraintLayout Figure : The Attributes window includes controls for 1 size ratio, 2 delete constraint, 3 height/width mode, 4margins, and 5 constraint bias.
  • 29. Android apps development Md. Moniruzzaman (Monir) Toolbar <resources> <!-- Base application theme. --> <style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar"> <!-- Customize your theme here. --> <item name="colorPrimary">@color/colorPrimary</item> <item name="colorPrimaryDark">@color/colorPrimaryDark</item> <item name="colorAccent">@color/colorAccent</item> </style> </resources> <android.support.v7.widget.Toolbar android:id="@+id/toolbar" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_alignParentStart="true" android:background="@color/colorPrimary" />
  • 30. Android apps development Md. Moniruzzaman (Monir) Toolbar @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); //getting the toolbar Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); //setting the title toolbar.setTitle("My Toolbar"); //placing toolbar in place of actionbar setSupportActionBar(toolbar); }
  • 31. Android apps development Md. Moniruzzaman (Monir) Setting up a Menu on the Toolbar Creating a Menu: <?xml version="1.0" encoding="utf-8"?> <menu xmlns:android="http://schemas.android.com/apk/res/android"> <item android:id="@+id/menuAbout" android:title="About" /> <item android:id="@+id/menuSettings" android:title="Settings" /> <item android:id="@+id/menuLogout" android:title="Logout" /> </menu>
  • 32. Android apps development Md. Moniruzzaman (Monir) Setting up a Menu on the Toolbar @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater menuInflater = getMenuInflater(); menuInflater.inflate(R.menu.menu, menu); return true; }
  • 33. Android apps development Md. Moniruzzaman (Monir) Handling Menu Clicks @Override public boolean onOptionsItemSelected(MenuItem item) { switch(item.getItemId()){ case R.id.menuAbout: Toast.makeText(this, "You clicked about", Toast.LENGTH_SHORT).show(); break; case R.id.menuSettings: Toast.makeText(this, "You clicked settings", Toast.LENGTH_SHORT).show(); break; case R.id.menuLogout: Toast.makeText(this, "You clicked logout", Toast.LENGTH_SHORT).show(); break; } return true; }
  • 34. Android apps development Md. Moniruzzaman (Monir) Navigation Drawer ● The navigation drawer is a UI panel that shows your app's main navigation menu. It is hidden when not in use, but appears when the user swipes a finger from the left edge of the screen:
  • 35. Android apps development Md. Moniruzzaman (Monir) Add a drawer to into layout <?xml version="1.0" encoding="utf-8"?> <!-- Use DrawerLayout as root container for activity --> <android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" android:id="@+id/drawer_layout" android:layout_width="match_parent" android:layout_height="match_parent" android:fitsSystemWindows="true"> <!-- Layout to contain contents of main body of screen (drawer will slide over this) --> <FrameLayout android:id="@+id/content_frame" android:layout_width="match_parent" android:layout_height="match_parent" />
  • 36. Android apps development Md. Moniruzzaman (Monir) Add a drawer to into layout <!-- Container for contents of drawer - use NavigationView to make configuration easier --> <android.support.design.widget.NavigationView android:id="@+id/nav_view" android:layout_width="wrap_content" android:layout_height="match_parent" android:layout_gravity="start" android:fitsSystemWindows="true“ app:menu="@menu/drawer_view" app:headerLayout="@layout/nav_header" /> </android.support.v4.widget.DrawerLayout>
  • 37. Android apps development Md. Moniruzzaman (Monir) Create the menu resource Create the menu resource with the corresponding file name. For example, at res/menu/drawer_view.xml: <?xml version="1.0" encoding="utf-8"?> <menu xmlns:android="http://schemas.android.com/apk/res/android" > <group android:checkableBehavior="single"> <item android:id="@+id/nav_camera" android:icon="@drawable/ic_menu_camera" android:title="@string/import" /> <item android:id="@+id/nav_gallery" android:icon="@drawable/ic_menu_gallery" android:title="@string/gallery" /> <item android:id="@+id/nav_slideshow" android:icon="@drawable/ic_menu_slideshow" android:title="@string/slideshow" /> <item android:id="@+id/nav_manage" android:icon="@drawable/ic_menu_manage" android:title="@string/tools" /> </group> </menu>
  • 38. Android apps development Md. Moniruzzaman (Monir) Handle navigation click events @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mDrawerLayout = findViewById(R.id.drawer_layout); NavigationView navigationView = findViewById(R.id.nav_view); navigationView.setNavigationItemSelectedListener( new NavigationView.OnNavigationItemSelectedListener() { @Override public boolean onNavigationItemSelected(MenuItem menuItem) { // set item as selected to persist highlight menuItem.setChecked(true); // close drawer when item is tapped mDrawerLayout.closeDrawers(); // Add code here to update the UI based on the item selected // For example, swap UI fragments here return true; } }); }
  • 39. Android apps development Md. Moniruzzaman (Monir) Android animation ● Adding animations to your app interface will give high quality feel to your android applications. Animations can be performed through either XML or android code. ● There are 3 types of Animations: ● Property Animations — They are used to alter property of objects (Views or non view objects). ● View Animations — They are used to do simple animations like changing size, position, rotation, control transparency. ● Drawable Animations —This is used to do animation using drawables. An XML file specifying various list of drawables is made which are run one by one just like a roll of a film. This is not much used so I won’t cover it.
  • 40. Android apps development Md. Moniruzzaman (Monir) Android Animation Using XML Create an xml file which defines type of animation to perform. This file should be located under anim folder under res directory (res ⇒ anim ⇒ animation.xml). If you don’t have anim folder in your res directory create one. Following is example of simple fade in animation.
  • 41. Android apps development Md. Moniruzzaman (Monir) Android Animation Using XML ● Create xml that defines the animation: fade_in.xml <?xml version="1.0" encoding="utf-8"?> <set xmlns:android="http://schemas.android.com/apk/res/android" android:fillAfter="true" > <alpha android:duration="1000" android:fromAlpha="0.0" android:interpolator="@android:anim/accelerate_interpolator" android:toAlpha="1.0" /> </set>
  • 42. Android apps development Md. Moniruzzaman (Monir) Loading Animation @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_fadein); txtMessage = (TextView) findViewById(R.id.txtMessage); // load the animation Animation animFadein = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.fade_in); }
  • 43. Android apps development Md. Moniruzzaman (Monir) Animation state listeners public class FadeInActivity extends Activity implements AnimationListener { animFadein.setAnimationListener(this); @Override public void onAnimationEnd(Animation animation) { // Take any action after completing the animation } @Override public void onAnimationRepeat(Animation animation) { // Animation is repeating } @Override public void onAnimationStart(Animation animation) { // Animation started } }
  • 44. Android apps development Md. Moniruzzaman (Monir) Start the animation You can start animation whenever you want by calling startAnimation on any UI element by passing the type of animation. In this example i am calling fade in animation on TextView: // start the animation txtMessage.startAnimation(animFadein); However instead of xml we can also use android code to create animation such like a class is ObjectAnimator ObjectAnimator rotationAnimator = ObjectAnimator.ofFloat(animateTextView, "rotation", 360f); rotationAnimator.setDuration(2000);
  • 45. Android apps development Md. Moniruzzaman (Monir) Creating Lists and Cards To create complex lists and cards with material design styles in your apps, you can use the RecyclerView and CardView widgets. Figure : The RecyclerView widget. RecyclerView provides these built-in layout managers: LinearLayoutManager shows items in a vertical or horizontal scrolling list. GridLayoutManager shows items in a grid. StaggeredGridLayoutManager shows items in a staggered grid. To create a custom layout manager, extend the RecyclerView.LayoutManager class.
  • 46. Android apps development Md. Moniruzzaman (Monir) RecyclerView <!-- A RecyclerView with some commonly used attributes --> <android.support.v7.widget.RecyclerView android:id="@+id/my_recycler_view" android:scrollbars="vertical" android:layout_width="match_parent" android:layout_height="match_parent"/> Once you have added a RecyclerView widget to your layout, obtain a handle to the object, connect it to a layout manager, and attach an adapter for the data to be displayed:
  • 47. Android apps development Md. Moniruzzaman (Monir) RecyclerView @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.my_activity); mRecyclerView = (RecyclerView) findViewById(R.id.my_recycler_view); // use this setting to improve performance if you know that changes // in content do not change the layout size of the RecyclerView mRecyclerView.setHasFixedSize(true); // use a linear layout manager mLayoutManager = new LinearLayoutManager(this); mRecyclerView.setLayoutManager(mLayoutManager); // specify an adapter (see also next example) mAdapter = new MyAdapter(myDataset); mRecyclerView.setAdapter(mAdapter); }
  • 48. Android apps development Md. Moniruzzaman (Monir) Adapter The adapter provides access to the items in your data set, creates views for items, and replaces the content of some of the views with new data items when the original item is no longer visible. public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> { private String[] mDataset; // Provide a reference to the views for each data item // Complex data items may need more than one view per item, and // you provide access to all the views for a data item in a view holder public static class ViewHolder extends RecyclerView.ViewHolder { // each data item is just a string in this case public TextView mTextView; public ViewHolder(TextView v) { super(v); mTextView = v; } }
  • 49. Android apps development Md. Moniruzzaman (Monir) Adapter // Provide a suitable constructor (depends on the kind of dataset) public MyAdapter(String[] myDataset) { mDataset = myDataset; } // Create new views (invoked by the layout manager) @Override public MyAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { // create a new view TextView v = (TextView) LayoutInflater.from(parent.getContext()) .inflate(R.layout.my_text_view, parent, false); // set the view's size, margins, paddings and layout parameters ViewHolder vh = new ViewHolder(v); return vh; }
  • 50. Android apps development Md. Moniruzzaman (Monir) Adapter // Replace the contents of a view (invoked by the layout manager) @Override public void onBindViewHolder(ViewHolder holder, int position) { // - get element from your dataset at this position // - replace the contents of the view with that element holder.mTextView.setText(mDataset[position]); } // Return the size of your dataset (invoked by the layout manager) @Override public int getItemCount() { return mDataset.length; } }
  • 51. Android apps development Md. Moniruzzaman (Monir) Different view in adapter To handle the case where you want different types of view for different rows. For instance, in a contacts application you may want even rows to have pictures on the left side and odd rows to have pictures on the right. In that case, you would use: @Override public int getViewTypeCount() { return 2; } @Override public int getItemViewType(int position) { return position % 2; }
  • 52. Android apps development Md. Moniruzzaman (Monir) Different view in adapter @Override public MainVH onCreateViewHolder(ViewGroup parent, int viewType) { int layoutRes; switch (viewType) { case VIEW_TYPE_HEADER: layoutRes = R.layout.item_header; break; case VIEW_TYPE_FOOTER: layoutRes = R.layout.item_footer; break; default: layoutRes = R.layout.content_swipe; break; } View v = LayoutInflater.from(parent.getContext()) .inflate(layoutRes, parent, false); return new MainVH(v); }
  • 53. Android apps development Md. Moniruzzaman (Monir) Create Cards CardView extends the FrameLayout class and lets you show information inside cards that have a consistent look across the platform. CardView widgets can have shadows and rounded corners. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" xmlns:card_view="http://schemas.android.com/apk/res-auto" ... > <!-- A CardView that contains a TextView --> <android.support.v7.widget.CardView xmlns:card_view="http://schemas.android.com/apk/res-auto" android:id="@+id/card_view" android:layout_gravity="center" android:layout_width="200dp" android:layout_height="200dp" card_view:cardCornerRadius="4dp"> <TextView android:id="@+id/info_text" android:layout_width="match_parent" android:layout_height="match_parent" /> </android.support.v7.widget.CardView> </LinearLayout>
  • 54. Android apps development Md. Moniruzzaman (Monir) Add Dependencies The RecyclerView and CardView widgets are part of the v7 Support Libraries. To use these widgets in your project, add these Gradle dependencies to your app's module: dependencies { compile 'com.android.support:cardview-v7:21.0.+' compile 'com.android.support:recyclerview-v7:21.0.+‘ }
  • 55. Android apps development Md. Moniruzzaman (Monir) Android ViewPager Android ViewPager widget is found in the support library and it allows the user to swipe left or right to see an entirely new screen. <android.support.v4.view.ViewPager android:id="@+id/viewpager" android:layout_width="match_parent" android:layout_height="match_parent“/> @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); ViewPager viewPager = (ViewPager) findViewById(R.id.viewpager); viewPager.setAdapter(new CustomPagerAdapter(this)); }
  • 56. Android apps development Md. Moniruzzaman (Monir) PagerAdapter public class CustomPagerAdapter extends PagerAdapter { private Context mContext; public CustomPagerAdapter(Context context) { mContext = context; } @Override public Object instantiateItem(ViewGroup collection, int position) { ModelObject modelObject = ModelObject.values()[position]; LayoutInflater inflater = LayoutInflater.from(mContext); ViewGroup layout = (ViewGroup) inflater.inflate(modelObject.getLayoutResId(), collection, false); collection.addView(layout); return layout; }
  • 57. Android apps development Md. Moniruzzaman (Monir) PagerAdapter @Override public void destroyItem(ViewGroup collection, int position, Object view) { collection.removeView((View) view); } @Override public int getCount() { return ModelObject.values().length; } @Override public boolean isViewFromObject(View view, Object object) { return view == object; } @Override public CharSequence getPageTitle(int position) { ModelObject customPagerEnum = ModelObject.values()[position]; return mContext.getString(customPagerEnum.getTitleResId()); }
  • 58. Android apps development Md. Moniruzzaman (Monir) PagerAdapter ● CustomPagerAdapter(Context context) : The constructor needs a Context reference. The context is saved as a member variable of the class since it’s used later to access the individual page layouts from the enum class ● instantiateItem : In this case, we use the enum and inflate the particular enum value’s associated layout. Then, we add the newly inflated layout to the ViewGroup(collection of Views) maintained by the PagerAdapter, and then we return that layout. The object being returned by this method is also used later on, as the second parameter in the isViewFromObject method ● destroyItem : This method removes a particular view from the ViewGroup maintained by the PagerAdapter ● getCount : It simply returns the number of views that will be maintained by the ViewPager. For this example, the count is the number of enum values in the model object ● isViewFromObject : This method checks whether a particular object belongs to a given position, which is made simple. As noted earlier, the second parameter is of type Object and is the same as the return value from the instantiateItem method ● getPageTitle : At a given position, we need to supply the PagerAdapter with a title. This usually manifests itself in the ActionBar as the Activity’s title, or sometimes tabs will hook into this method for labelling each tab. In this case we’ve kept it for labelling only
  • 59. Android apps development Md. Moniruzzaman (Monir) Assignment Details Create a Application which have a navigation drawer with two tab option (Home and Food). 1. Home: User can see all order list he/she has already done. 2. Food: User can order any food item from list of category item including every item have a multiple image showing option by swiping Note: i) All the item design and layout design will be using only constraint layout and co- ordinator layout. ii) Home and Food tab will be fragment. Basic features should be same what I draw on the white board. (Duration 4 days including today)
  • 60. Android apps development Md. Moniruzzaman (Monir) Assignment Guidelines  (There will be toolbar , list of data will be shown using recyclerview cardview and adapter )  For showing multiple image there will be used viewpager, adapter  Data list could be static.  For any help conduct with me or any android developer
  • 61. Android apps development Md. Moniruzzaman (Monir) Resources • https://developer.android.com/guide/components/fundamentals.html#Components • https://developer.android.com/guide/platform/index.html • https://developer.android.com/guide/components/activities/activity-lifecycle.html • https://developer.android.com/guide/components/fragments.html • https://developer.android.com/training/basics/fragments/creating.html • https://developer.android.com/guide/topics/ui/declaring-layout.html • https://developer.android.com/training/basics/fragments/fragment-ui.html • https://developer.android.com/guide/topics/resources/providing- resources.html#ResourceTypes • https://www.androidhive.info/2013/06/android-working-with-xml-animations/ • https://medium.com/mindorks/a-beginners-guide-to-implement-android-animations-part-1-2- part-series-b5fce1fc85 • https://developer.android.com/training/material/lists-cards.html#RecyclerView • https://developer.android.com/training/constraint-layout/ • https://www.tutorialspoint.com/android/index.htm