[go: up one dir, main page]

0% found this document useful (0 votes)
68 views26 pages

Unit 2

The document outlines the directory structure of an Android project, detailing the purpose of various folders such as Java, Resource, Manifests, and Gradle Scripts. It also explains how to implement UI components like DatePicker, TimePicker, Spinner, and Menus, providing examples of XML layouts and Java code. Additionally, it emphasizes the importance of using XML for defining menus and the different types of menus available in Android applications.

Uploaded by

Ashok
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
68 views26 pages

Unit 2

The document outlines the directory structure of an Android project, detailing the purpose of various folders such as Java, Resource, Manifests, and Gradle Scripts. It also explains how to implement UI components like DatePicker, TimePicker, Spinner, and Menus, providing examples of XML layouts and Java code. Additionally, it emphasizes the importance of using XML for defining menus and the different types of menus available in Android applications.

Uploaded by

Ashok
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 26

The directory structure of an Android Project.

The android app project will contain different types of app modules, source code files, and resource
files.

Java Folder
This folder will contain all the java source code (.java) files which we’ll create during the
application development, including JUnit test code. Whenever we create any new
project/application, by default the class file MainActivity.java will create automatically under
the package.
Resource (res) folder
The resource folder is the most important folder because it contains all the non-code sources
like images, XML layouts, and UI strings for our android application.

Drawable Folder (res/drawable)

It will contain the different types of images as per the requirement of application. It’s a best
practice to add all the images in a drawable folder other than app/launcher icons for the
application development.

Layout Folder (res/layout)

This folder will contain all XML layout files which we used to define the user interface of
our application. Following is the structure of the layout folder in the android application.

Mipmap Folder (res/mipmap)


This folder will contain app / launcher icons that are used to show on the home screen. It will
contain different density type of icons such as hdpi, mdpi, xhdpi, xxhdpi, xxxhdpi, to use
different icons based on the size of the device.

Following is the structure of the mipmap folder in the android application.

Values Folder (res/values)


This folder will contain various XML files, such as strings, colors, style definitions and a static
array of strings or integers. Following is the structure of the values folder in android
application.

Manifests Folder
This folder will contain a manifest file (AndroidManifest.xml) for our android application.
This manifest file will contain information about our application such as android version,
access permissions, metadata, etc. of our application and its components. The manifest file will
act as an intermediate between android OS and our application.
Following is the structure of the manifests folder in the android application.

Gradle Scripts

In android, Gradle means automated build system and by using this we can define a build
configuration that applies to all modules in our application. In Gradle build.gradle (Project),
and build.gradle (Module) files are useful to build configurations that apply to all our app
modules or specific to one app module.

Following is the structure of Gradle Scripts in the android application.

Android Layout File (activity_main.xml)

The UI of our application will be designed in this file and it will contain Design and Text
modes. It will exists in the layouts folder and the structure of activity_main.xml file in Design
mode like as shown below.
Android Manifest File (AndroidManifest.xml)
Generally, our application will contain multiple activities and we need to define all
those activities in the AndroidManifest.xml file. In our manifest file, we need to mention the
main activity for our app using the MAIN action and LAUNCHER category attributes in
intent filters (<intent-filter>). In case if we didn’t mention MAIN action or LAUNCHER
category for the main activity, our app icon will not appear in the home screen’s list of apps.

Following is the default code of AndroidManifest.xml file which is generated by our


HelloWorld application.

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


<manifest
xmlns:android=http://schemas.android.com/apk/res/android package="com.helloworld" >

<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme" >
<activity android:name=".MainActivity" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
DatePicker in Android
DatePicker dialog is seen used in many android applications where we have to select the date.
This widget is mostly seen in the hotel reservation applications for travel booking applications.
With the help of this widget, we can simply pick the date from the DatePicker dialog. In this
article, we will take a look at How to implement Date Picker in Android.

DatePicker offers two display modes:

1. Calendar View: Displays a complete calendar for date selection.

2. Spinner View: Displays selectable values for day, month, and year in a scrollable
spinner format.

Example:
activity_main.xml
<DatePicker
android:id="@+id/picker"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="28dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.491"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />

<TextView
android:id="@+id/textview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="160dp"
android:textSize="70px"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.104"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/picker"
app:layout_constraintVertical_bias="1.0" />

<Button
android:id="@+id/button"
android:layout_width="209dp"
android:layout_height="80dp"
android:layout_marginBottom="80dp"
android:text="Submit"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.797"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/picker"
app:layout_constraintVertical_bias="1.0" />

MainActivity.java

DatePicker picker;
TextView textview;
Button button;

picker = (DatePicker) findViewById(R.id.picker);


textview = (TextView) findViewById(R.id.textview);
button = (Button) findViewById(R.id.button);

textview.setText("Current Date: " + dateConverter());

button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
textview.setText("Change Date: " + dateConverter());
}
});
}
public String dateConverter()
{
StringBuilder obj = new StringBuilder();
obj.append((picker.getMonth() + 1)+"/");
obj.append(picker.getDayOfMonth()+"/");
obj.append(picker.getYear());
return obj.toString();
}
TimePicker in Android
TimePicker Dialog is used in many applications where we have to book appointments based
on a specific time. This widget is seen in the applications where we have to select specific time
slots. In this article, we will take a look at How to use TimePicker Dialog on
Android. TimePicker provides two display modes:

1. Clock Mode: Displays an analog clock-style interface for time selection.


2. Spinner Mode: Presents hour and minute values in a scrollable spinner format.
Example:

<TimePicker
android:id="@+id/picker"
android:layout_width="371dp"
android:layout_height="367dp"
android:layout_marginTop="40dp"
android:background="@color/colorPrimary"
android:padding="30px"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.4"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
android:timePickerMode="spinner"/>

<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="52dp"
android:textSize="50px"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.498"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/picker" />

Java file
TextView time;
TimePicker simpleTime;
time = (TextView)findViewById(R.id.textView);
simpleTime = (TimePicker) findViewById(R.id.picker);
simpleTime.setIs24HourView(false);
time.setText("The Time is: "+simpleTime.getCurrentHour()+"
"+simpleTime.getCurrentMinute());
simpleTime.setOnTimeChangedListener(new TimePicker.OnTimeChangedListener()
{
@Override
public void onTimeChanged(TimePicker view, int hourofDay, int minute)
{
time.setText("The Time is: "+hourofDay+ " :"+minute);
} }); }
Android Spinner (Dropdown List)
In android, Spinner is a view that allows a user to select one value from the list of values. The
spinner in android will behave same as a dropdown list in other programming
languages. Generally, the android spinners will provide a quick way to select one item from
the list of values and it will show a dropdown menu with a list of all values when we click or
tap on it. By default, the android spinner will show its currently selected value and by using
Adapter we can bind the items to spinner objects. We can populate our Spinner control with
list of choices by defining an ArrayAdapter in our Activity file. Generally, the Adapter pulls
data from sources such as an array or database and converts each item into a result view and
that’s placed into the list.

Android Adapter
In android, Adapter will act as an intermediate between the data sources and adapter views
such as ListView, Gridview to fill the data into adapter views. The adapter will hold the data
and iterates through an items in data set and generate the views for each item in the list.

Create Android Spinner in XML Layout File


In android, we can create Spinner in XML layout file using <Spinner> element with
different attributes like as shown below.
<Spinner android:id="@+id/spinner1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>

Android Spinner Example

activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="match_parent">
<TextView
android:id="@+id/txtVw"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="50dp"
android:layout_marginTop="150dp"
android:text="Select User:"
android:textStyle="bold"
android:textSize="15dp" />
<Spinner
android:id="@+id/spinner1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="@+id/txtVw"
android:layout_toRightOf="@+id/txtVw" />
</RelativeLayout>
MainActivity.java

package com.tutlane.spinnerexample;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity implements


AdapterView.OnItemSelectedListener {
String[] country = { "India", "USA", "England", "Srilanka", "Australia" };
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Spinner spin = (Spinner) findViewById(R.id.spinner1);
ArrayAdapter adapter = new ArrayAdapter(this, android.R.layout.simple_spinner_item,
country);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spin.setAdapter(adapter);
spin.setOnItemSelectedListener(this);
}
@Override
public void onItemSelected(AdapterView<?> arg0, View arg1, int position,long id) {
Toast.makeText(getApplicationContext(), "Selected User:
"+country[position] ,Toast.LENGTH_SHORT).show();
}
}
}
Menu in Android

Menus are an essential part of Android UI design, offering users a smooth and consistent
navigation experience. With the help of menu, users can experience a smooth and consistent
experience throughout the application. To define menus efficiently and maintain clean code,
Android recommends using XML menu resources instead of programmatically creating menus
in your activities or fragments. This approach ensures better organization and easier
maintenance.

How to define Menu in XML File?

Android Studio provides a standard XML format for the type of menus to define menu items.
We can simply define the menu and all its items in XML menu resource instead of building the
menu in the code and also load menu resource as menu object in the activity or fragment used
in our android application. Here, we should create a new folder menu inside of our project
directory (res/menu) to define the menu and also add a new XML file to build the menu with
the following elements. Below is the example of defining a menu in the XML file
(menu_example.xml).

Way to create menu directory and menu resource file

To create the menu directory just right-click on res folder and navigate to res > New > Android
Resource Directory. Give Resource type and Directory name as menu. One directory will
be created under res folder under the name of menu.

To create xml resource file simply right-click on menu folder and navigate to New > Menu
Resource File. Give name of file as menu_example. One menu_example.xml file will be
created under menu folder.

menu_example.xml:

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


<menu
xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:id="@+id/file"
android:title="File" >

<!-- "File" submenu -->


<menu>
<item
android:id="@+id/create_new"
android:title="Create New"
/>
<item
android:id="@+id/open"
android:title="Open"
/>
</menu>
</item>
</menu>

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


<menu xmlns:android="http://schemas.android.com/apk/res/android" > <item
android:id="@+id/search_item"
android:title="Search" />
<item android:id="@+id/upload_item"
android:title="Upload" />
<item android:id="@+id/copy_item"
android:title="Copy" />
<item android:id="@+id/print_item"
android:title="Print" />
<item android:id="@+id/share_item"
android:title="Share" />
<item android:id="@+id/bookmark_item"
android:title="BookMark" />
</menu>

Android Different Types of Menus

In android, we have three types of Menus available to define a set of options and actions in our
android applications. The Menus in android applications are the following:

Android Options Menu: is a primary collection of menu items in an android application and
is useful for actions that have a global impact on the searching application.

Android Context Menu: is a floating menu that only appears when the user clicks for a long
time on an element and is useful for elements that affect the selected content or context frame.

Android Popup Menu: displays a list of items in a vertical list which presents the view that
invoked the menu and is useful to provide an overflow of actions related to specific content.
Various UI components and their Properties
Example:

activity_main.xml

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


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/main"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"
android:orientation="vertical">

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Registration Form"
android:layout_gravity="center_horizontal"
android:layout_marginTop="20dp"
android:textSize="20sp"
android:textStyle="bold"/>
<EditText
android:id="@+id/et_name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:hint="Name"
android:autofillHints="name"
android:inputType="textPersonName"/>

<EditText
android:id="@+id/et_email"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:hint="Email"
android:autofillHints="emailAddress"
android:inputType="textEmailAddress"/>

<EditText
android:id="@+id/et_phoneNumber"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:hint="Phone No."
android:autofillHints="phone"
android:inputType="phone"/>

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Gender"
android:textSize="15sp"
android:layout_marginTop="10dp"
android:layout_marginStart="10dp"/>

<RadioGroup
android:id="@+id/rg_gender"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_marginStart="10dp"
android:layout_marginEnd="10dp">

<RadioButton
android:id="@+id/rb_male"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:paddingHorizontal="10dp"
android:layout_weight="1"
android:text="Male"/>

<RadioButton
android:id="@+id/rb_female"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:paddingHorizontal="10dp"
android:layout_weight="1"
android:text="Female"/>

</RadioGroup>

<EditText
android:id="@+id/et_address"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:hint="Address"
android:autofillHints="postalAddress"
android:inputType="textPostalAddress"/>

<EditText
android:id="@+id/et_department"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:hint="Department"
android:autofillHints="text"
android:inputType="text"/>

<CheckBox
android:id="@+id/cv_terms_condition"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="I agree with Terms &amp; Conditions"
android:textSize="14sp"
android:layout_marginStart="10dp"/>

<ImageButton
android:id="@+id/ib_next"
android:layout_width="100dp"
android:layout_height="wrap_content"

android:layout_gravity="center_horizontal"/>

</LinearLayout>
Theme and Style in Android

A style is a collection of attributes that specifies the appearance for a single View. A style can
specify attributes such as font color, font size, background color, and much more.
A theme is a collection of attributes that's applied to an entire app, activity, or view hierarchy
not just an individual view. When you apply a theme, every view in the app or activity applies
each of the theme's attributes that it supports. Themes can also apply styles to non-view
elements, such as the status bar and window background.

Create and apply a style


To create a new style, open your project's res/values/styles.xml file. For each style you want
to create, follow these steps:
1. Add a <style> element with a name that uniquely identifies the style.
2. Add an <item> element for each style attribute you want to define. The name in each item
specifies an attribute you otherwise use as an XML attribute in your layout. The value in
the <item> element is the value for that attribute.

Defining Styles

A style is defined in an XML resource that is separate from the XML that specifies the layout.
This XML file resides under res/values/ directory of your project and will have <resources> as
the root node which is mandatory for the style file. The name of the XML file is arbitrary, but
it must use the .xml extension.

You can define multiple styles per file using <style> tag but each style will have its name that
uniquely identifies the style. Android style attributes are set using <item> tag as shown below

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


<resources>
<style name="CustomFontStyle">
<item name="android:layout_width">fill_parent</item>
<item name="android:layout_height">wrap_content</item>
<item name="android:capitalize">characters</item>
<item name="android:typeface">monospace</item>
<item name="android:textSize">12pt</item>
<item name="android:textColor">#00FF00</item>/>
</style>
</resources>

The value for the <item> can be a keyword string, a hex color, a reference to another resource
type, or other value depending on the style property.

public class MainActivity extends ActionBarActivity {


Button b1;

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

b1=(Button)findViewById(R.id.button);
b1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(MainActivity.this,"YOUR
MESSAGE",Toast.LENGTH_LONG).show();
}
});
}
}

Following will be the content of res/values/style.xml file which will have addition style
CustomButtonStyle defined –

style.xml

<resources>

<!-- Base application theme. -->

<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">


<!-- Customize your theme here. -->
<item name="colorPrimary">@color/colorPrimary</item>
<item name="colorPrimaryDark">@color/colorPrimaryDark</item>
<item name="colorAccent">@color/colorAccent</item>
</style>

<style name="CustomButtonStyle">
<item name="android:layout_width">100dp</item>
<item name="android:layout_height">38dp</item>
<item name="android:capitalize">characters</item>
<item name="android:typeface">monospace</item>
<item name="android:shadowDx">1.2</item>
<item name="android:shadowDy">1.2</item>
<item name="android:shadowRadius">2</item>
<item name="android:textColor">#000000</item>
<item name="android:gravity" >center</item>
<item name="android:layout_margin" >3dp</item>
<item name="android:textSize" >5pt</item>
<item name="android:background">#70ff106d</item>
<item name="android:shadowColor" >#70ff106d</item>
</style>

</resources>

Following will be the content of res/layout/activity_main.xml file –

activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin"
tools:context=".MainActivity">

<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Custom Button Style "
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:textSize="30dp" />

<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Tutorials point "
android:textColor="#ff87ff09"
android:textSize="30dp"
android:layout_below="@+id/textView1"
android:layout_centerHorizontal="true" />

<ImageButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/imageButton"
android:src="@drawable/abc"
android:layout_below="@+id/textView2"
android:layout_centerHorizontal="true" />

<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
style="@style/CustomButtonStyle"
android:text="New Button"
android:id="@+id/button"
android:layout_below="@+id/imageButton"
android:layout_alignLeft="@+id/imageButton"
android:layout_alignStart="@+id/imageButton"
android:layout_alignRight="@+id/textView2"
android:layout_alignEnd="@+id/textView2" />

</RelativeLayout>

Following will be the content of res/values/strings.xml to define two new constants –

string.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">myapplication</string>
</resources>

Following is the default content of AndroidManifest.xml −


Theme Demo

AndroidManifest.xml
package com.example.themedemo;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends Activity {


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

//--- find both the buttons---


Button sButton = (Button) findViewById(R.id.button_s);
Button lButton = (Button) findViewById(R.id.button_l);
// -- register click event with first button ---
sButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// --- find the text view --
TextView txtView = (TextView) findViewById(R.id.text_id);

// -- change text size --


txtView.setTextSize(20);
}
});

// -- register click event with second button ---


lButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// --- find the text view --
TextView txtView = (TextView) findViewById(R.id.text_id);

// -- change text size --


txtView.setTextSize(24);
}
});
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}

Following will be the content of res/values/style.xml file which will have addition style
CustomButtonStyle defined –

style.xml

<resources>

<!--
Base application theme, dependent on API level. This theme is replaced
by AppBaseTheme from res/values-vXX/styles.xml on newer devices.
-->

<style name="AppBaseTheme" parent="android:Theme.Light">


<!--
Theme customizations available in newer API levels can go in
res/values-vXX/styles.xml, while customizations related to
backward-compatibility can go here.
-->
</style>

<!-- Application theme. -->


<style name="AppTheme" parent="AppBaseTheme">
<!-- All customizations that are NOT specific to a particular API-level can go here. -->
<item name="android:capitalize">characters</item>
<item name="android:typeface">monospace</item>
<item name="android:shadowDx">1.2</item>
<item name="android:shadowDy">1.2</item>
<item name="android:shadowRadius">2</item>
<item name="android:textColor">#494948</item>/>
<item name="android:gravity" >center</item>
<item name="android:layout_margin" >3dp</item>
<item name="android:textSize" >5pt</item>
<item name="android:shadowColor" >#000000</item>
</style>

<!-- Custom Style defined for the buttons. -->


<style name="CustomButtonStyle">
<item name="android:layout_width">100dp</item>
<item name="android:layout_height">38dp</item>
</style>

</resources>

Following will be the content of res/layout/activity_main.xml file –

activity_main.xml

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


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

<Button
android:id="@+id/button_s"
style="@style/CustomButtonStyle"
android:text="@string/button_small"
android:onClick="doSmall"/>

<Button
android:id="@+id/button_l"
style="@style/CustomButtonStyle"
android:text="@string/button_large"
android:onClick="doLarge"/>

<TextView
android:id="@+id/text_id"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:capitalize="characters"
android:text="@string/hello_world" />

</LinearLayout>

Following will be the content of res/values/strings.xml to define two new constants –

strings.xml

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


<resources>
<string name="app_name">ThemeDemo</string>
<string name="action_settings">Settings</string>
<string name="hello_world">Hello world!</string>
<string name="button_small">Small Font</string>
<string name="button_large">Large Font</string>
</resources>
Recycler View in Android
Recycler view is part of of Android jetpack. It is a UI component that allows the development
to create a scrolling list. It is a ViewGroup used to render the data set with the help of adapter
and viewholder.
Major component of RecyclerView:
• RecyclerView.Adapter:
RecyclerView includes a new kind of Adapter. It’s a similar approach to the ones we
already used but with some peculiarities such as a required ViewHolder for handling
Views. We will have to override two main methods first one to inflate the view and its
viewholder and another one to bind the data to the view. The main good thing in this is
that the first method is called only when we really need to create a new view.

• ViewHolder:
ViewHolder is used to store the reference of the View’s for one entry in the
RecyclerView. A ViewHolder is a static inner class in our Adapter which holds
references to the relevant view’s. By using these references our code can avoid time
consuming findViewById() method to update the widgets with new data.

• Layout Managers:
In Android a RecyclerView needs to have a Layout Manager and an Adapter to be
instantiated. Layout Manager is a very new concept introduced in RecyclerView for
defining the type of Layout which RecyclerView should use. It contains the references
for all the views that are filled by the data of the entry. We can create a Custom Layout
Manager by extending RecyclerView.LayoutManager Class but RecyclerView
Provides three types of in-built Layout Managers.

1) Linear Layout Manager – It is used for displaying the data items in a horizontal or
vertical scrolling List.

// get the reference of RecyclerView


RecyclerView recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
LinearLayoutManager linearLayoutManager = new
LinearLayoutManager(getApplicationContext());
recyclerView.setLayoutManager(linearLayoutManager);

It is used to create a vertical LinearLayoutManager. In this we need to set only one


parameter i.e used to set the context the current Activity.

2) GridLayoutManager –
It is used to show the items in grid format. If we need to display items in grid format
then we can use GridLayoutManager. In simple words we can say that we use the
GridLayoutManager for displaying RecyclerView as a GridView.

// get the reference of RecyclerView


RecyclerView recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
GridLayoutManager gridLayoutManager = new
GridLayoutManager(getApplicationContext(),3);
recyclerView.setLayoutManager(gridLayoutManager);

It is used to create a Vertical GridLayoutManager. In this constructor first parameter


is used to set the current context and second parameter is used to set the spanCount
means the number of columns in the grid.
3) StaggeredGridLayoutManager-
It is used to show the items in staggered Grid.

StaggeredGridLayoutManager(int spanCount, int orientation):


It is used to create a StaggeredGridLayoutManager with given parameters. First
parameter is used to set spanCount means number of columns if orientation is
vertical or number of rows if orientation is horizontal, Second Parameter is used to
set the Orientation, it should be vertical or horizontal.

// get the reference of RecyclerView


RecyclerView recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
StaggeredGridLayoutManager staggeredGridLayoutManager = new
StaggeredGridLayoutManager(3, LinearLayoutManager.VERTICAL);
recyclerView.setLayoutManager(staggeredGridLayoutManager);
Internal working of RecyclerView:

• ViewPort: All visible view item on the screen of recyclerview is part of Android
ViewPort. It varies when screen sized increases or decrease like in the above example
viewport size is 3.
• Scrap View: The immediate view item of recyclerview that just gone away either from
top / bottom of screen. Also the view that is just moved from view port. This view is
not longer going to display and moving into mechanism to recycle the view with new
data.
• Recycle View: After getting view into scrap stage it is going to recycler for further new
data.
• Dirty View: Your old view is recycled and ready to attach with new data.
• Binding View: New data is will set over the recycled item view and going to visible
into recyclerview.
• Visible View: Visible views are part of android viewport. it may going to scrap view
or it may just came from binding with new data form recylerview.

You might also like