Android_Studio_Brief_W4
Android_Studio_Brief_W4
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)
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
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.
</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>
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:
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.
}
});
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.
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
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
@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
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
<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."
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
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.
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.
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
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;
}
}
});
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.
}
}
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:
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 {
}
}
3.Step 3: there should be error on the class ViewHolder. Right click and choose create constructor
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