0% found this document useful (0 votes)
11 views

Android_Studio_Brief_W4

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

Android_Studio_Brief_W4

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

ANDROID DEVELOPMENT MATERIALS

I. The process of programming in Android


1. Designing: create your design on a layout
 Drag and drop or creating controls by code
 Identify controls with unique identity with the syntax
android:id="@+id/txtMain"
2. Mapping: Map your controls to your variables in the java (code behide) file
 Create a variable (can be global) with correspondent datatype as your control:
TextView, Button.
 Map your variable to your correspondent control using the syntax
findViewById(R.id.<ID of your control>)
 Map your controls’ events to your method using the setOn… method:
objectButton.setOnClickListener(new … choose the event from the auto Suggesstion
list and enter for default creation)
3. Coding: start coding with your mapping controls variables
Note some way to use Android Studio suggestion:
 For errors(red serrated underline): right click on the error and choose Show context actions or
press Ctrl+Enter
 Press Ctrl+Space to open auto suggestion
 Press Alt+Enter to add import missing library
Example:
Create a new Android project and add some views:
 A TextView with text value:”Enter your name”
 An EditText with text value:””
 A Button with text value: press
Write code for the OnClick event of the button. Set the text value of the EditText to “The
button was clicked”
Hints: Create the application following the three steps above
II. Resources (R)
1. Access id resources
In XML In Java
android:id="@+id/txtMain" R.id.txtMain

2. Access strings resources


Define strings, string arrays, and plurals (and include string formatting and styling). You can
Define values such as booleans, integers, dimensions, colors, and other arrays in res/values/ but
each accessed from unique R sub-classes (such as R.bool, R.integer, R.dimen, etc.).
In XML In Java
@string/app_name getResources().getString(R.string.app_name)
or
R.string.app_name
3. Access color resources:
Define a color resources that changes based on the View state.
In XML In Java
@color/Blueabc getResources().getColor(R.color.Blueabc)

Example:
Add some value to the Resources:
 A String with value: “Enter your name”, tag name: Enter
 A String with value: “Press Me”, tag name: Press
 A String with value: “Hello World!”, tag name: hello_world
 A Blue color with value “#0000FF”, tag name: Blue
Make some changes to your previuos application:
 Using Enter for the EditText text value
 Using Press for the Button text value
 Using hello_world for the hint of TextView
 When the user click the button change the text color of the TextView to Blue

III. TextView
NO Attribute Description Methods related
1 android:text Text to display setText (int resid,
TextView.BufferType type)
2 android:background Background color setBackgroundColor(int color)
3 android:textColor Text color setTextColor(int color)
4 android:textSize Size of the text: sp (scaled pixels based on
preferred font size)
5 android:layout_height Set the height of the TextView(
wrap_content, match_parent)
6 android:layout_width Set the width of the TextView(
wrap_content, match_parent)

IV. EditView / or plain text


NO Attribute Description Methods related
1 android:text Text to display or inputted getText().toString()
2 android:textSize Size of the text: sp (scaled pixels based on
preferred font size)
3 android:textColor Text color setTextColor(int color)
4 android:hint Provide hint for the control when the
Text is empty
5 android:inputType Set the type for input: text,
textPassword, number(only allow for
input number)
6 android:drawableLeft The drawable to be drawn to the left of the
text
android:drawableLeft=
"@drawable/icon_number_50"
https://icons8.com
7 android:drawableRight The drawable to be drawn to the right of the
text
android: drawableRight =
"@drawable/icon_number_50"
8
V. Layout
1. LinearLayout
LinearLayout is a view group that aligns all children in a single direction, vertically or horizontally.
You can specify the layout direction with the android:orientation attribute.

android:orientation = “horizontal” android:orientation = “vertical”

NO Attribute Description Methods related


1 android:orientation specify the layout direction:
vertical or horizontal
2 android:weightSum Defines the maximum weight sum of the
layout so that its children can define their
percentage of presentation in the view.
The chidren use android:layout_weight
to determine the percentage.
For example:
A layout with android:weightSum=10
and orientation= vertical
There can be 4 children with
layout_weight (2-3-4-1) and the
layout_height=”0dp”
2. ConstraintLayout
A ConstraintLayout is a android.view.ViewGroup which allows you to position and size widgets in a
flexible way. After drag and drop the control in to the layout, infer Constraints to automatically
create constraints or specify the constraints for each control using the 4 little circles of the choosen
control.
ConstraintLayout allow positionning and size widgets in a flexible way

For each
constraint you can
specify a margin
number in layout
Property

Use 4 little circles of the choosen control to make constraints for it.
Center modification
VI. Margin vs Padding

NO Attribute Description Methods related


1 android:layout_margin Specifies extra space on the left, top,
right and bottom sides of this view.
2 android:layout_marginBottom Specifies extra space on the bottom
side of this view.
3 android:layout_marginLeft Specifies extra space on the left side
of this view.
4 android:layout_marginRight Specifies extra space on the right
side of this view.
5 android:layout_marginTop Specifies extra space on the top side of
this view.
6 android:paddingTop Specifies extra space on the top side of
the content of this view
7 android:paddingLeft Specifies extra space on the left side of
the content of this view
8 android:paddingRight Specifies extra space on the right side
of the content of this view
9 android:paddingBottom Specifies extra space on the bottom
side of the content of this view

Example: Create a Login form using ConstraintLayot with serveral controls:


 Textview: User Login
 EditText: User name for input User name
 EditText: Password for input Password
 A buton: Log me in!
When the user press the button show the following message box:
 If the user hasn’t input User name then: “Please input user name!”
 If the user hasn’t input Password then: “Please input password!”
 If the user has input both then: “Congratulation! You have master the
ConstraintLayout.”

VII. Activity & Intent


1. Activity
An activity represents a single screen in your app with an interface the user can interact with. For
example, an email app might have one activity that shows a list of new emails, another activity to
compose an email, and another activity for reading individual messages. Your app is a collection of
activities that you either create yourself, or that you reuse from other apps.
Although the activities in your app work together to form a cohesive user experience in your app, each
one is independent of the others. This enables your app to start activities in other apps, and other apps
can start your activities (if your app allows it). For example, a messaging app you write could start an
activity in a camera app to take a picture, and then start the activity in an email app to let the user share
that picture in email.
Typically, one activity in an app is specified as the "main" activity, which is presented to the user when
launching the application for the first time. Each activity can then start other activities in order to
perform different actions.

Each time a new activity starts, the previous activity is stopped, but the system preserves the activity in
a stack (the "back stack"). When the user is done with the current activity and presses the Back button, it
is popped from the stack (and destroyed) and the previous activity resumes.
2. Intent
All Android activities are started or activated with an intent. Intents are message objects that make a
request to the Android runtime to start an activity or other app component in your app or in some other
app
When your app is first started from the device home screen, the Android runtime sends an intent to your
app to start your app's main activity (the one defined with the MAIN action and the LAUNCHER
category in the Android Manifest). To start other activities in your app, or request that actions be
performed by some other activity available on the device, you build your own intents with the Intent
class and call the startActivity() method to send that intent
There are two types of intents in Android:
 Explicit intents: specify the receiving activity (or other component) by that activity's fully-
qualified class name. Use an explicit intent to start a component in your own app (for example,
to move between screens in the user interface), because you already know the package and class
name of that component.
 Implicit intents: do not specify a specific activity or other component to receive the intent.
Instead you declare a general action to perform in the intent. The Android system matches your
request to an activity or other component that can handle your requested action. You'll learn
more about implicit intents in a later chapter.
We will work on then Explicit intents:
 Start an explicit intents, use the following syntax:
Intent messageIntent = new Intent(An application context, The specific component to start).
 An application context: <name of the current activity>.this
 The specific component to start: the activity that we want to open ShowMessageActivity.class.
For example:
Intent messageIntent = new Intent(<name of the current
activity>.this, ShowMessageActivity.class);
startActivity(messageIntent);
 Add data to the intent
messageIntent.putExtra(EXTRA_MESSAGE, "this is my message");
 EXTRA_MESSAGE is a string
 "this is my message" is the value to send
 Retrieve the data from the intent:
Bundle extras = getIntent().getExtras();
String name = extras.getString(NAME);
 Start an explicit intents to get result
To start an activity to do something and then get back the result use the following syntax:
 For API level lower than 31
startActivityForResult(messageIntent, REQUEST_CODE);
 For API level from 31:
Intent messageIntent = new Intent(MainActivity.this,
ShowMessageActivity.class);
ActivityResultLauncher<Intent> messageIntent Launcher =
registerForActivityResult(new
ActivityResultContracts.StartActivityForResult(),
result->{
if (result.getResultCode() == RESULT_OK)
{
// Handle the result here (task added)
}
});
addTaskLauncher.launch(AddActivityIntent);
 REQUEST_CODE: should be a static integer variables with names that include REQUEST
For example
public static final int PHOTO_REQUEST = 1;
public static final int PHOTO_PICK_REQUEST = 2;
public static final int TEXT_REQUEST = 3;
 Return a response from the launched activity
Intent returnIntent = new Intent();
returnIntent.putExtra("Back", "Back ok");
setResult(RESULT_OK,returnIntent);
finish();
The following constants are Adnroid predefined:
 RESULT_OK: the request was successful
 RESULT_CANCELED: the user cancelled the operation.
 RESULT_FIRST_USER. for defining your own result codes.
 Get back data in the main activity
public void onActivityResult(int requestCode, int resultCode,
Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_CODE) {
if (resultCode == RESULT_OK && data !=null) {
String reply =
data.getStringExtra(“Back”);
// process data
}
}
}

Example: keep using the previos Login form, add a new Activity call SecondActivity. In the
SecondActivity, add some controls:
 A TextView with text value:”Hi! ”+ the account that user has input from the
MainActivity.+ “. Wellcome to the Second Activity”
 A Textview with value: “Please say something!”
 An EditText for inputted
 A button with value: “Go Back!”
 When user click the Go Back! Button, go back to the main screen and show the
message that the user has inputted.

3. Intent send & receive object


To send object as data in the intent, do as the followng steps:
 Step1: The class of the object must implement Serializable.
public class Task implements Serializable
 Step 2: the send intent do as usual:
Intent messageIntent = new Intent(MainActivity.this, AddTaskActivity.class);
messageIntent.putExtra("taskobj",task);
startActivityForResult(messageIntent, REQUEST_CODE_EDIT);
 The receiver call getSerializableExtra method
Intent intent=getIntent();
if (intent.getSerializableExtra("taskobj")!=null){
takobj=(Task) intent.getSerializableExtra("taskobj");
edtTaskName.setText(takobj.getName());
edtDueDate.setText(takobj.getDueDate());
}

VIII. Toast / or show message


A toast provides simple feedback about an operation in a small popup. It only fills the amount of space
required for the message and the current activity remains visible and interactive. Toasts automatically
disappear after a timeout
Use the makeText() method returns a properly initialized Toast object.
CharSequence text = "Hello toast!";
int duration = Toast.LENGTH_SHORT;

Toast toast = Toast.makeText(this /* MyActivity */, text, duration);


toast.show();
----Week 3----
IX. Styles vs Themes
1. Styles
A style is a collection of attributes that specifiy the appearance for a View or window.
A style can specifile attributes such as font color, font size, background color… (View Color concept of
Material design)
Example
 Button style
<style name="myButton">
<item name="backgroundTint">#52634F</item>
<item name="android:textSize">18sp</item>
<item name="cornerRadius">5dp</item>
</style>
 Cardview style
<style name="CardView.">
<item name="cardElevation">4dp</item>
<item name="cardBackgroundColor">@color/md_theme_light_primaryContainer</item>
<item name="contentPadding">8dp</item>
<item name="cardCornerRadius">5dp</item>

</style>
2. Theme
A theme is a collection of attributes that’s applied to an entire app, activity or view hierachy (not just an
individual view)
Themes can also apply styles to non-view elements, such as the status bar and window background.
There are two theme modes: normal theme and night theme.

For example:
 Define color for the whole project using Material Design
<style name="Base.Theme.Style_and_theme"
parent="Theme.Material3.DayNight.NoActionBar">
<!-- Customize your light theme here. -->
<item name="colorPrimary">@color/md_theme_light_primary</item>
<item name="colorOnPrimary">@color/md_theme_light_onPrimary</item>
<item name="colorSecondary">@color/md_theme_light_secondary</item>
<item name="colorOnSecondary">@color/md_theme_light_onSecondary</item>
</style>
 Make all buttons in the project with the same style
<style name="myButton" parent="Widget.MaterialComponents.Button">
<item name="backgroundTint">@color/md_theme_light_secondary</item>
<item name="android:textSize">18sp</item>
<item name="cornerRadius">5dp</item>
</style>
Add new item to theme
<item name="materialButtonStyle">@style/myButton</item>

3. Create Landscape qualifier/variation


You can create a landscape qualifier or variation to modify the layout in landscape mode
4. Material concepts about color
Link concepts about color of material design
https://m3.material.io/styles/color/the-color-system/color-roles
link palette generator: use this to generate color theme
https://m3.material.io/theme-builder#/custom
5. Material concepts about font
 Material define font scale
Link fonts design
https://m2.material.io/design/typography/the-type-system.html#type-scale

 Add custom font to the project

 Define font style


<style name="TextAppearance.App.Headline1"
parent="TextAppearance.MaterialComponents.Headline1">
<item name="fontFamily">@font/roboto_mono_light</item>
<item name="android:textSize">96sp</item>
</style>
<style name="TextAppearance.App.Headline2"
parent="TextAppearance.MaterialComponents.Headline2">
<item name="fontFamily">@font/roboto_mono_light</item>
<item name="android:textSize">60sp</item>
</style>
Use for TextView
android:textAppearance="@style/TextAppearance.App.Headline1"

X. RadioGroup & RadioButton


Radio buttons allow the user to select one option from a set. RadioButton of the same group should be
put in a RadioGroup so that only one button within the group will be choosen.

RadioGroup Properties
android:orientation vertical/horizontal
Event
setOnCheckedChangeListener new RadioGroup.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(RadioGroup
radioGroup, int i) {
//i is the id of the radiobutton in it
RadioButton rbChecked=findViewById(i);
Toast.makeText(MainActivity.this, rbChecked.getText()+"
is selected", Toast.LENGTH_SHORT).show();
}
}
Method
getCheckedRadioButtonId() Return the id of the selected radiobutton
RadioButton Properties
checked Set whether a radiobutton is checked or not: True/false

XI. Checkbox
Checkboxes let the user select one or more options from a set. Typically, you present checkbox options
in a vertical list.
Event
setOnCheckedChangeListener new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton
compoundButton, boolean b) {
//b is true if the checkbox is checked
if(b){
Toast.makeText(MainActivity.this, "Checkbox
is checked", Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(MainActivity.this, "Checkbox
is unchecked", Toast.LENGTH_SHORT).show();
}
}
}
Method
isChecked() Return true if the checkbox is checked

XII. DatePicker
Android provides controls for picking a date or time using dialogs. The pickers automatically adjust to
the user’s locale. It is recommended to use a DialogFragment to host a picker, so the DialogFragment
will contain a DatePickerDialog.
It is rather complicated to define and use the datepicker, so I have define a DatePickerFragment class.
You just need to copy and paste to your java folder and use it.
To show a datepicker just use the following code:
DialogFragment newFragment = new
DatePickerFragment(view,DatetimeFormat);
newFragment.show(getSupportFragmentManager(), "datePicker");
view: a TextView or EditText that the date will be shown after choosen.
DatetimeFormat: "dd/MM/yyyy" or "yyyy/MM/dd"
XIII. Spinner & Adapter
Spinners allow a user to select a value from a list (similar to a dropdown list). There are two mode:

Dropdown – this is like a dropdown list Dialog – this opens the list in a dialog filling the
whole screen

 XML code for defining a Spinner and populate it with predefined xml array:

The countryArray can be defined in the values.xml as follow


<string-array name="countryArray">
<item>England</item>
<item>Northern Ireland</item>
<item>Scotland</item>
<item>Wales</item>
</string-array>
 Java code for populating Spinner and event mapping
Steps Code
1. Drag/Drop and Spinner sp=findViewById(R.id.spinner);
Mapping
2. Prepare data ArrayList<String> arrcountries=new ArrayList<>();
source arrcountries.add("England");
arrcountries.add("Northern Ireland");
arrcountries.add("Scotland");
arrcountries.add("Wales");
3. Create Adapter ArrayAdapter adapter=new ArrayAdapter(MainActivity.this,
androidx.appcompat.R.layout.support_simple_spinner_dropdown_item,
arrcountries
);
4. Set data source sp.setAdapter(adapter);
for the spinner
5. Mapping event sp.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> adapterView, View view,
int i, long l) {

Toast.makeText(MainActivity.this, arrcountries.get(i),
Toast.LENGTH_SHORT).show();
}

@Override
public void onNothingSelected(AdapterView<?> adapterView) {

}
});
 To get current selected item of a spinner
String text = sp.getSelectedItem().toString();
XIV. AlertDiaglog
A dialog is a small window that prompts the user to make a decision or enter additional information. A
dialog does not fill the screen and is normally used for modal events that require users to take an action
before they can proceed.

Instansiation an alert dialog


AlertDialog.Builder alertDialog=new
AlertDialog.Builder(MainActivity.this)
;
Method
setTitle("Clear all data!"); Set the title for the dialog
setIcon(R.mipmap.ic_launcher); Set the icon for the dialog
setMessage(message); Set the message for the dialog
show(); Show the alert dialog
Events
setNegativeButton The No button
setNegativeButton("No", new
DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface
dialogInterface, int i) {

}
});
setPositiveButton The Yes button
alertDialog.setPositiveButton("Yes", new
DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface
dialogInterface, int i) {
}
});
XV. Listview & Adapter
Displays a vertically-scrollable collection of views, where each view is positioned
immediatelybelow the previous view in the list.
A list view is an adapter view that does not know the details, such as type and contents, of the views
it contains. Instead list view requests views on demand from a ListAdapter as needed, such as to
display new views as the user scrolls up or down.
In order to display items in the list, call setAdapter(android.widget.ListAdapter) to associate an
adapter with the list.

ListView working steps


1. Drag, drop and mapping ListView lvCountries;
lvCountries=findViewById(R.id.lvMain);
2. Prepare data in an For example data of countries:
ArrayList ArrayList<String> arListCountries=new ArrayList<>();
arListCountries.add("Vietnam");
arListCountries.add("England");
arListCountries.add("Afghanistan");
arListCountries.add("Albania");
arListCountries.add("Algeria");
arListCountries.add("Andorra");
3. Create an Syntax: ArrayAdapter(Context context, // the context
Adapter(ArrayAdapter) int resource, //refer to designed layout
to map data and layout to List<T> objects //list of data
the ListView )
ArrayAdapter adapter=new ArrayAdapter(
MainActivity.this,
android.R.layout.simple_list_item_1,
arListCountries);

android.R.layout.simple_list_item_1 is a predifined layout for


a simple list with only one string line.
You can define your own layout with many things such as
TextView, checkbox…
4. Set Adapter for the lvCountries.setAdapter(adapter);
Listview
ListView Events
setOnItemClickListener AdapterView<?> parent, //The AdapterView where the click
happened.
View view, // The view within the AdapterView that was clicked
int position, // The position of the view in the adapter
long id // The row id of the item that was clicked
)
setOnItemLongClickListener AdapterView<?> parent, //The AdapterView where the click
happened.
View view, // The view within the AdapterView that was clicked
int position, // The position of the view in the adapter
long id // The row id of the item that was clicked
)
Adapter method
adapter.notifyDataSetChanged() When add, update, delete data source (ArrayList) let the adapter
; notify the Listview
getFilter().filter(String query); This method will filter the datasource on the query parameter and
show the result back to the listview

Example:
Create an android application, which contains:
 A TextView with value: List of Countries
 A ListView: show a list of countries.
 When user click on a line item show the
postion of the item
 When user click and keep for a while show
the string value of the item
XVI. ListView & Custom Adapter

Data Source Adapter ListView


 Item 1
DataSource Title 1
(text1, text2)
 Item 2 Text1 Text2 Description 1
(text1, text2)
 Item 3 Title 2
(text1, text2) Description 2
Layout
Title
Title 3
Description
Description 3

ListView allows us to design the layout of each item as we want. To do that we learn about
LayoutInflater class. LayoutInflater provide a way to process a predefined XML layout to generate a
view for java, so after that we can put it on the listview.
LayoutInflater inflater = context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
Or LayoutInflater inflater = LayoutInflater.from(context);
Context: can be MainActivity.this
The job of LayoutInflater is to read an XML layout file and convert its attributes into a View in Java
code. Once we have a LayoutInflater object, we can use the inflate method to convert an XML layout
file into a View in Java. There are two inflate methods with different numbers of parameters:
View view = layoutInflater.inflate(int resource, ViewGroup parent)
Or View view = layoutInflater.inflate(int resource, ViewGroup parent, boolean attachToRoot)
resource: the XML layout
parent:the view group that store the xml layout. In this case the parent is the listview
attachToRoot: true or false. True mean put it in the view group now, false mean not put it in the view
group now
The step to create a custom listview
1. Design a layout resource file (not the activity) for each item of the listview
2. Create a class for storing data source as the data contain many information such as name, phone,
address
3. Create a custom Adapter which extend the BaseAdapter.
=> see the following steps:
1. Create a Layout Resource file

Design the file using constrain layout


2. Create a java class to store information

3. Create a custom Adapter which extend the BaseAdapter.

public class ContactAdapter extends BaseAdapter {


private Context context;
private int layout;
private ArrayList<Contact> contacts;

public ContactAdapter(Context context, int layout, ArrayList<Contact> contacts)


{
this.context = context;
this.layout = layout;
this.contacts = contacts;
}

@Override
public int getCount() {
//return the number of listview items
return contacts.size();
}

@Override
public Object getItem(int i) {
return null;
}

@Override
public long getItemId(int i) {
return 0;
}
@Override
public View getView(int i, View view, ViewGroup viewGroup) {
//return each line of the view
context.getSystemService(context.LAYOUT_INFLATER_SERVICE);
LayoutInflater inflater = LayoutInflater.from(context);
view=inflater.inflate(layout,viewGroup, false);

TextView txtTen=view.findViewById(R.id.txtTen);
TextView txtPhone=view.findViewById(R.id.txtPhone);
TextView txtAddress=view.findViewById(R.id.txtAddress);
ImageView imgAvatar=view.findViewById(R.id.imgAvatar);

txtTen.setText(contacts.get(i).getName());
txtPhone.setText(contacts.get(i).getPhone());
txtAddress.setText(contacts.get(i).getAddress());
imgAvatar.setImageResource(contacts.get(i).getAvatar());
return view;
}
}

The class has context, layout and contacts as the constructor has three input parameters like this. There
are two important methods:
getCount(): return the total number of the list
getView(): Return the item view for each line for the listview
After we create the customer adapter we can use it as normal adapter

XVII. ListView, Custom Adapter & add event for sub item in the custom layout

Layout of each item ListView

1. Set setOnItemClickListener, setOnItemLongClickListener for the ListView


When making a custom layout and use it as a template for each item line to be able to alert the
setOnItemClickListener and setOnItemLongClickListener, you must add attribute
android:focusable="false" for each sub-item in the custom line layout.
After that you can implement setOnItemClickListener and setOnItemLongClickListener for your
listview as usual.
2. Set event for items within the custom layout: there are two cases.
 The first case is that the event just affect the data or just affect the items in the custom
layout: for example, the check button in the layout above. When user check or uncheck it
just updates the property of the object data. Therefore, just do as usual.
 The second case is that the event affect the activiy component or open new activity… in
this case we must find a way to invoke the methods which are defined in the activities.
To do that we need to use polymorphism approaches.
- We first define an interface
private CustomListeners customListeners;//property to store the object of the interface
type
public interface CustomListeners {
public void editTask(Task task);
}
Within the Customer adapter class. The interface provide all the method name that we
well want to use but not the implementation. Those methods will be implemented in the
activity.
- Secondly, we provide a method to set a object that implemented the interface above:
public void setCustomListeners(CustomListeners customListeners) {
this.customListeners = customListeners;
}
- Thirdly, set event for each item in the method getView as usual and call the method
of object customListeners as you wish.
- Fourly, provide implementation of the interface in the activity
MainActivity extends AppCompatActivity implements TaskAdapter.CustomListeners
- Lastly, set the mainActivity object for the adapter
taskAdapter.setCustomListeners(MainActivity.this);
Data Source Adapter ListView
 Item 1 DataSource Title 1
(text1, text2) Text1 Text2 Description 1
 Item 2
Button
(text1, text2)
 Item 3
(text1, text2) Title 1
Layout
Description 1
Title
Button
Description
Activity implement Button
CustomListeners Title 1
Description 1
Function 1
CustomListener Button

Function 2 Function 1

Function 2
--Week 4--
XVIII. Custom dialog
We can use custom dialog for simple form which will run faster and easier than open a new Activity. To
create a custom dialog follow the steps:
1. Create a xml layout for the custom dialog. Drag and drop controls in the layout as usual.
2. Use class Dialog in the java Activity file to create new dialog object and Call method
setContentView to set the custom design layout for the dialog
3. Do mapping for all the controls in the custom dialog layout.
4. Call method show tho show the dialog
The steps can be carried out like this:
1. Step 1: Create a xml layout for the custom dialog.
Right click on the layout folder and choose New>Layout Resource File

Name the custom dialog as you wish

Design the layout as usual


You can use constrain layout for easier design. However you should change the width of the
layout to about 300dp instead of match_parent as it was generated. Because with the width
match_parent the location of controls on the dialog later can be wrong with the design.
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="300dp"
android:layout_height="match_parent"
xmlns:android="http://schemas.android.com/apk/res/android">

<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="0dp"
android:text="User login"
android:textSize="20sp"
android:textStyle="bold"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />

<EditText
android:id="@+id/edtUserName"
android:layout_width="241dp"
android:layout_height="41dp"
android:layout_marginTop="20dp"
android:ems="10"
android:hint="User name"
android:inputType="text"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/textView" />

<EditText
android:id="@+id/edtPassword"
android:layout_width="241dp"
android:layout_height="41dp"
android:layout_marginTop="20dp"
android:ems="10"
android:hint="Password"
android:inputType="text"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/edtUserName" />

<Button
android:id="@+id/btLogin"
android:layout_width="88dp"
android:layout_height="wrap_content"
android:layout_marginStart="50dp"
android:layout_marginTop="20dp"
android:text="Login"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/edtPassword" />

<Button
android:id="@+id/btClose"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:layout_marginEnd="50dp"
android:text="Close"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toBottomOf="@+id/edtPassword" />
</androidx.constraintlayout.widget.ConstraintLayout>

2. Use class Dialog in the java Activity file to create new dialog object
Dialog dialog=new Dialog(MainActivity.this);
dialog.setContentView(R.layout.custom_dialog); // the custom dialog u have designed
3. Do mapping for all the controls in the custom dialog layout
Button btLogin=dialog.findViewById(R.id.btLogin);
Button btClose=dialog.findViewById(R.id.btClose);

btLogin.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Toast.makeText(MainActivity.this, "Button login is clicked!",
Toast.LENGTH_SHORT).show();
}
});

btClose.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
dialog.dismiss();
}
});
4. Call method show tho show the dialog
dialog.show();

XIX. Menu
Menus are a common user interface component in many types of applications. To provide a familiar and
consistent user experience, you should use the Menu APIs to present user actions and other options in
your activities. There are three types of menu in an android application
1. Option menu/ Toolbar menu
The options menu is the primary collection of menu items for an activity. It's where you should place
actions that have a global impact on the app, such as "Search," "Compose email," and "Settings."

Click the three dots icon to open the toolbar


menu The toolbar menu
To create toolbar menu follow the steps below:
 Step1: Create a menu folder under res folder
New Android Resource Directory

 Step2: create menu layout


Create a Menu Resource File

Name it as menu_toolbar
 Step3: open the menu_toolbar.xml and put the code as follow
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item android:id="@+id/setting"
android:title="Setting"
app:showAsAction="never"/>
<item android:id="@+id/Share"
android:title="Share"/>
<item android:id="@+id/Search"
android:icon="@drawable/search_50"
android:title="Search"
app:showAsAction="always"
app:actionViewClass="android.widget.SearchView"/>
</menu>

showAsAction – never means that the item will be in the overflow menu
showAsAction – ifRoom means that the item will be displayed in the toolbar if there is enough
room for it
app:showAsAction="always" mean that the item will always be displayed in the toolbar
app:actionViewClass="android.widget.SearchView" mean the item will served as a search view
if user click on it

 Step3: Drag and drop Toolbar to the activity and make it on the top of the activity

 Step4: Add some javacode for the MainActivity


- Code for the OnCreateOptionMenu
 @Override
public boolean onCreateOptionsMenu(Menu menu) {

getMenuInflater().inflate(R.menu.menu_toolbar,menu);

return super.onCreateOptionsMenu(menu);

}
- Code for onCreate of the activity
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

Toolbar mytoolbar=findViewById(R.id.toolbar);
setSupportActionBar(mytoolbar);
- Code for Menu item click
 @Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {

if (item.getItemId()==R.id.setting){
Toast.makeText(this, "Setting is selected",
Toast.LENGTH_SHORT).show();
}else if(item.getItemId()==R.id.Share){
Toast.makeText(this, "Share is selected", Toast.LENGTH_SHORT).show();
}else if(item.getItemId()==R.id.Search){
Toast.makeText(this, "Search is selected", Toast.LENGTH_SHORT).show();

return super.onOptionsItemSelected(item);
}
The item is the clicked item. We can get it’s id from the method getItemID()
2. Popup menu
A popup menu displays a list of items in a vertical list that's anchored to the view that invoked the menu.
It's good for providing an overflow of actions that relate to specific content or to provide options for a
second part of a command. Actions in a popup menu should not directly affect the corresponding content
—that's what contextual actions are for. Rather, the popup menu is for extended actions that relate to
regions of content in your activity.

To create popup menu follow the steps below:


 Step1: Create menu folder (if not created)
 Step2: Add menu_popup.xml resource file and put the code as follow
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="@+id/add" android:title="Add"/>
<item android:id="@+id/update" android:title="Update"/>
<item android:id="@+id/delete" android:title="Delete"/>
</menu>
 Drag and drop a button or any that you want to pin your popup menu
 Add some javacode in the onCreate event of Main Activity
btPopupMenu=findViewById(R.id.bt_PopupMenu);
btPopupMenu.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
PopupMenu popupMenu=new PopupMenu(MainActivity.this,btPopupMenu);

popupMenu.getMenuInflater().inflate(R.menu.menu_popup,popupMenu.getMenu());
popupMenu.show();
popupMenu.setOnMenuItemClickListener(new
PopupMenu.OnMenuItemClickListener() {
@Override
public boolean onMenuItemClick(MenuItem menuItem) {
if (menuItem.getItemId()==R.id.add){
Toast.makeText(MainActivity.this, "Add is selected",
Toast.LENGTH_SHORT).show();
}else if(menuItem.getItemId()==R.id.update){
Toast.makeText(MainActivity.this, "Update is selected",
Toast.LENGTH_SHORT).show();
}else if(menuItem.getItemId()==R.id.delete){
Toast.makeText(MainActivity.this, "Delete is selected",
Toast.LENGTH_SHORT).show();

}
return false;
}
});

}
});
- First we create a popup menu on the button
PopupMenu popupMenu=new PopupMenu(MainActivity.this,btPopupMenu);
- And then we use the design layout menu_popup.xml for the popup menu
popupMenu.getMenuInflater().inflate(R.menu.menu_popup,popupMenu.getMenu());
- Next we add event listener for OnMenuItemClickListener to handle the event when user click
a menu item. The method menuItem.getItemId() is important as it return the id of the clicked
menu item.

XX. Fragment
A Fragment represents a reusable portion of your app's UI. A fragment defines and manages its own
layout, has its own lifecycle, and can handle its own input events. Fragments can't live on their own.
They must be hosted by an activity or another fragment. The fragment’s view hierarchy becomes part
of, or attaches to, the host’s view hierarchy.

1. To use Fragment in your project follow the steps below:


 Step1: Create fragment layout
 Step2: Create fragment java file to manage the layout. Make some changes in the code.
 Step3: Prepare a container to put the fragment inside. The container can be a layout(contrain
layout, linear layout or frame layout…). Drag and drop the layout on your activity to prepare for
a container
 Step4: Write java code in the activity to add the fragment that you have designed to the
container.
 Step5: Write java code to make communicate between the activity and the fragment
2. The steps can be done as follow:
 Step1: Create fragment layout
Right click on layout folder and choose New>Layout Resource file
Name the fragment layout as you wish

Design the fragment as usual


 Step2: Create fragment java file to manage the layout. Make some changes in the code.
Right click on the working folder of java to add a new Java Class

Name the java file as you wish. But it should correlate with the name of your fragment for easy
management
Make changes to the genrated code

The changes are follow

You can copy the following codes:


public class Fragment_a extends Fragment {
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup
container, Bundle savedInstanceState) {

View view=inflater.inflate(R.layout.fragment_a,container,false);
return view;
}
}
 Step3: Prepare a container (in the activity) to put the fragment inside. The container can be a
layout(contrain layout, linear layout or frame layout…). Drag and drop the layout on your
activity to prepare for a container
 Step4: Write java code in the activity to add the fragment that you have designed to the
container. I will write code to handle OnClick event for button Add Fragment so that when the
user click on the button. The fragment will be added to the container
Button btAddFragment;
btAddFragment=findViewById(R.id.btAddFragment);
btAddFragment.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
FragmentManager fragmentManager=getFragmentManager();
FragmentTransaction fragmentTransaction=fragmentManager.beginTransaction();
Fragment_a fragA=new Fragment_a();

fragmentTransaction.replace(R.id.Container,fragA,"fragA");
fragmentTransaction.commit();
}
});
Some explaination for the code above:
- We need to create FragmentManager by method getFragmentManager();
- Create FragmentTransaction by beginTransaction() from the manager
- Create the fragment that we have designed Fragment_a fragA=new Fragment_a();
- After that, we use replace method of fragmentTransaction to add the fragment to the
Container and give it a tag (“fragA”) for later use.
- At last, we commint the trasaction => All are finished.
3. Communicate from the activity to the fragment.
Now you can add another button to the MainActivity to make communication with the items in the
Fragment
When click the button on the main activity will
result in the next image
The result

 Step 1: Create methods in the fragment java class so that the main activity can call the method.
This is Encapsulation. It help the code easy to use, to read, to understand and also easy for
maintenance
 public class Fragment_a extends Fragment {
EditText edtFragmentAEditText;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup
container, Bundle savedInstanceState) {

View view=inflater.inflate(R.layout.fragment_a,container,false);
edtFragmentAEditText=view.findViewById(R.id.edtFragmentAEditText);

return view;
}

public void SetText(String text){


edtFragmentAEditText.setText(text);
}
}
-
The first thing is to map the edit text in the fragment with a variable. We do that in
the OnCreateView:
edtFragmentAEditText=view.findViewById(R.id.edtFragmentAEditText);
The different is that we must use method findViewById from the view object
- After that we can make a method to do any thing related to the mapping variables.
For example, create a method SetText to put a text to the EditText in the fragment
 Step 2: Add some java code in the Main Activity
Button btContactFragment=findViewById(R.id.btContactFragment);
btContactFragment.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Fragment_a fragA = (Fragment_a) getFragmentManager().findFragmentByTag("fragA");
if (fragA!=null){
Toast.makeText(MainActivity.this, "A is the current fragment",
Toast.LENGTH_SHORT).show();
fragA.SetText("Hello! This text is from the main Activity");
}
}
});
We make code for the OnClick event of button btContactFragment in the main activity. In the
event, we do as follow:
- Find the current fragment bay tag: Fragment_a fragA = (Fragment_a)
getFragmentManager().findFragmentByTag("fragA"). The fragA is the tag we
named when we add the fragment.
- Call the method in the fragment: fragA.SetText("Hello! This text is from the main
Activity");

4. Communicate from the fragment back to the class.


With the same approache, to communicate with Main Activity from the fragment. We need to make a
method in the Main Activity, so that the fragment can call the method. This is once again, the
ecapsulation in oop.
 Step1: Create a method in the Main Activity:
public void MainActivitySetText(String text){
txtMainTextView.setText(text);
}
The txtMainTextView is the textview in the main activity
 Step2: in the Fragment add java code to call the method of the Main Activity
btFragmentAButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
MainActivity mainActivity=(MainActivity) getActivity();
mainActivity.MainActivitySetText("Hello! I am from Fragment A");

}
});
First we need to getActivity() and cast it to the activity which it is store, in this case is the Main
Activity. Then call the method of the activity.

XXI. Implicit intent(Camera/photo gallery…)


1. ImageView
Image is use to displays image resources, for example Bitmap or Drawable resources. ImageView is
also commonly used to apply tints to an image and handle image scaling.
Use setImageBitmap(Bitmap bm) to set the image as content for it
NO Attribute Description Methods related
1 android:src Set value to display image setImageBitmap(Bitmap bm)
set the image as content for it
2 tools:srcCompat Set value to display image
3 android:textColor Text color
4 android:scaleType fitXY: set this value to fix the size of
imageview

2. Open Camera and get image


To open camera use implicit intent
Intent intent=new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (intent.resolveActivity(getPackageManager()) != null) {
startActivityForResult(intent,REQUEST_CODE_CAMERA);
}
Where you define your constant REQUEST_CODE_CAMERA for later check condition in getting
back the result.
In the OnActivityResult add the following code to set image from the camera for the ImageView
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent
data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_CODE_CAMERA && resultCode==RESULT_OK && data !=null)
{
Bitmap thumbnail=(Bitmap) data.getExtras().get("data");
imgAvatar.setImageBitmap(thumbnail);

}
}
3. Get image from photo gallery
We also use implicit intent to open the photo gallery
Intent intent=new Intent(Intent.ACTION_PICK);
intent.setType("image/*");
if (intent.resolveActivity(getPackageManager()) != null) {
startActivityForResult(intent,REQUEST_CODE_PICK_IMAGE);
}
And in the OnActivityResult add some code to get the photo
if(requestCode == REQUEST_CODE_PICK_IMAGE && resultCode==RESULT_OK && data !=null){
Uri uri=data.getData();
InputStream inputStream= null;
try {
inputStream = getContentResolver().openInputStream(uri);
Bitmap bitmap= BitmapFactory.decodeStream(inputStream);
imgAvatar.setImageBitmap(bitmap);
} catch (FileNotFoundException e) {
throw new RuntimeException(e);
}

}
4. Make a call
Intent intent = new Intent(Intent.ACTION_DIAL);
intent.setData(Uri.parse("tel:0909758112"));
if (intent.resolveActivity(getPackageManager()) != null) {
startActivity(intent);
}
For the common implicit intent see the document below
https://developer.android.com/guide/components/intents-common

XXII. SQLite
SQLite is a opensource SQL database that stores data to a text file on a device. Android comes in with
built in SQLite database implementation.
To use SQLite we follow the steps below:
1. Create a java class which extend SQLiteOpenHelper
2. Add required method and constructor
3. Add some code for execute non result query(Create, update, insert, delete) and getdata for query
that have results
 Steps to use SQLite
1. Create a java class which extend SQLiteOpenHelper
Create a Java Class

Name it as Database
You will have the following file
Then extend SQLiteOpenHelper. Then your code as follow with some errors:

2. Add required method and constructor


Then you right click and choose Implement methods

Then your code is as follow


Right click again and choose Create constructor matching super

Then you have this one


Then you can add the following code for quering
// Query does not return results: Create, Insert, Update, Delete
public void Execute(String query){
SQLiteDatabase database=getWritableDatabase();
database.execSQL(query);
}

// Query return results: Select

public Cursor Getdata(String query){


SQLiteDatabase database=getReadableDatabase();
return database.rawQuery(query,null);
}

As the Getdata return a cursor, so to get date use the following code
ArrayList<String> arrCountries=new ArrayList<>();
Cursor dataContact=database.Getdata("Select * from Country");
while (dataContact.moveToNext()){
String name=dataContact.getString(1);
arrCountries.add(name);
}
The first column is number 0
 Some SQL code
You can look at this
https://www.tutorialspoint.com/sqlite/index.htm
Create table if not Exists Country(ID integer primary key autoincrement,
Name varchar(200))
Select * from Country
Insert into Country values(null,’Vietnam’)
Insert into Country values(null,’US’)
Example: Create an application to show list of countries from sqlite database
 Use SQLite Helper to store data of Countries so that when the application is turn off, data can
still reload
 OnCreate select data from country table and store in an arrraylist
 Create adapter to map data from the list to the normal layout
(android.R.layout.simple_list_item_1)
 Set adapter for the listview
 You can try add, update or delete country as well

To reduce difficulties, I have create a Database.java for you so that you can use it. In the class there are
two method that can help you to create and drop table:
 CreateTable(Table table)
database=new Database(this,"Country",null,1);
Database.Table country= database.new Table("Country");
Database.Table.Column col1=country.new Column("ID","Integer",true,true);
Database.Table.Column col2=country.new
Column("Name","Varchar(200)",false,false);
country.AddColumn(col1);
country.AddColumn(col2);
database.CreateTable(country);
 DropTable(Table table)
Call to drop a table
XXIII. RecyclerView
0.Create a layout for each line item of the RecyclerView
1.Step 1: Create a java class as you wish, for example ContactAdapter
2.Step 2: Within the class you mus create a sub class call ViewHolder which extend the
RecyclerView.ViewHolder. Your code should look as below
public class ContactAdapter {

public class ViewHolder extends RecyclerView.ViewHolder{

}
}
3.Step 3: there should be error on the class ViewHolder. Right click and choose create constructor

4. Step 4: add extend to class ContactAdapter as follow


public class ContactAdapter extends RecyclerView.Adapter<ContactAdapter.ViewHolder>
5.Step5: right click on the class ContactAdapter and choose implement method. Let implement all
methods
Your class should look like this

Step 6: create an array to store a list of data. In this case I create an arraylist to store a list of
Contacts.
ArrayList<Contact> arrContact;
Don’t forget to create a class to store information
Step7: create a constructor for the ContactAdapter
public ContactAdapter(ArrayList<Contact> arrContact) {
this.arrContact = arrContact;
}
Step8: change code in getItemCount()
@Override
public int getItemCount() {
return arrContact.size();
}
Step9: Declare all element in the view of each line in the ViewHolder class
public class ViewHolder extends RecyclerView.ViewHolder{
public TextView txtTen,txtPhone,txtAddress;

ImageView imgAvatar;
public ViewHolder(@NonNull View itemView) {
super(itemView);
this.txtTen=itemView.findViewById(R.id.txtTen);
this.txtPhone=itemView.findViewById(R.id.txtPhone);
this.txtAddress=itemView.findViewById(R.id.txtAddress);
this.imgAvatar=itemView.findViewById(R.id.imgAvatar);
}
}
Step10:Add code to the onCreateViewHolder event
public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View v=
LayoutInflater.from(parent.getContext()).inflate(R.layout.list_item,parent,false);
return new ViewHolder(v);
}
the list_item is the layout that you have designed in step0
Step11: set value for each element in the event onBindViewHolder
public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
holder.txtAddress.setText(arrContact.get(position).getAddress());
holder.imgAvatar.setImageResource(arrContact.get(position).getAvatar());
holder.txtTen.setText(arrContact.get(position).getName());
}

XXIV. ss

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy