Here we will learn how to use the ListView class and component to display data in rows as a List view. The list view is scrollable and it can display text, buttons, checkboxes, etc. Data for the list view is loaded through a Java class (an Activity).
We will use here a text view and a check box. The list view uses the model shoppinglist. A shopping list app is used here as an example.
Create Android layout file for the rows of the list
Create the file layout_row.xml with this content:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent">
<CheckBox
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/checkbox"
android:text="Buy"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/shoppingitem"
android:layout_marginLeft="15dp"
android:textSize="22sp"
android:text="shoppingitem"/>
</LinearLayout>
This defines the layout of a row of the list view. Later we will create a list of this row layout and access the checkbox component (has the id "checkbox") and the text view (has the id "shoppingitem").
Add List view to the main layout file "activity_main.xml"
This layout file contains only the List View to keep this introduction of ListView easy to understand.
Add the component ListView as shown here:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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:orientation="vertical">
<ListView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:id="@+id/shoppinglistview">
</ListView>
</LinearLayout>
Create Java (model) class "Shopping.java"
Create a Java class that will be used for a List array of the list view. It contains here the boolean variable isMarked, that saves if the checkbox is checked. But this class has also a String variable which saves the name of the shopping item.
public class Shopping {
private boolean isMarked;
private String shoppingItem;
public String getShoppingItem() {
return shoppingItem;
}
public void setShoppingItem(String shoppingItem) {
this.shoppingItem = shoppingItem;
}
public boolean getMarked() {
return isMarked;
}
public void setMarked(boolean marked) {
isMarked = marked;
}
}
Create adapter class "ShoppingAdapter.java"
This class must extend (command "extends") the class "BaseAdapter". It contains the following instance variables: Context variable and ArrayList with the before created "Shopping" class. You must override six functions.
The class contains the following:
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
public class ShoppingAdapter extends BaseAdapter {
private Context context;
public static ArrayList<Shopping> modelShoppingList;
public ShoppingAdapter(Context context, ArrayList<Shopping> modelShoppingList) {
this.context = context;
this.modelShoppingList = modelShoppingList;
}
@Override
public int getViewTypeCount() {
return getCount();
}
@Override
public int getItemViewType(int position) {
return position;
}
@Override
public int getCount() {
return modelShoppingList.size();
}
@Override
public Object getItem(int position) {
return modelShoppingList.get(position);
}
@Override
public long getItemId(int position) {
return 0;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
final ViewHolder holder;
if (convertView == null) {
holder = new ViewHolder(); LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.shoppinglistview, null, true);
holder.checkBox = (CheckBox) convertView.findViewById(R.id.checkbox);
holder.shoppingitem = (TextView) convertView.findViewById(R.id.shoppingitem);
convertView.setTag(holder);
}else {
// Method getTag() creates the viewHolder object as a tag and returns it to the view
holder = (ViewHolder)convertView.getTag();
}
holder.checkBox.setText("Checkbox No. "+position);
holder.shoppingitemText.setText(modelShoppingList.get(position).getShoppingItem());
holder.checkBox.setChecked(modelShoppingList.get(position).getSelected());
//Save this component in view ID 1
holder.checkBox.setTag(1, convertView);
holder.checkBox.setTag(position);
holder.checkBox.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Integer listPosition = (Integer) holder.checkBox.getTag();
Toast.makeText(context, "You clicked Checkbox "+pos, Toast.LENGTH_SHORT).show();
//Set display of checkbox
if(modelShoppingList.get(listPosition).getSelected()){
modelShoppingList.get(listPosition).setSelected(false);
}else {
modelShoppingList.get(listPosition).setSelected(true);
}
}
});
return convertView;
}
private class ViewHolder {
protected CheckBox checkBox;
private TextView shoppingitemText;
}
}
The content of the view is programmed in the function getView(). In the function onClick() (called through a OnClickListener on the checkbox) we define what should happen, if a checkbox is clicked. The component of the layout file (view) layout_row.xml is saved in a holder variable class "holder.checkBox". The holder variable or variables are created in the class ViewHolder in this same file. The view with its content is saved as a tag, which has an ID. Here we use the ID 1.
It is recommended to save the IDs for the view in the file "integer.xml". You have to create that file in the res/values directory. There you can store Integer values, which can be accessed like this in the Java code: "R.integer.YOUR_ID"
An "integer.xml" file looks like this:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<integer name="MY_INTEGER_VARIABLE">1</integer>
</resources>
You can also extend some functionality in the function onClick() in the above created class "ShoppingAdapter.java".
If you would like to edit or access components in the list row, then you can call them like this:
//Load view (Shopping list row) and components in view through this command
View shoppingitemRow = (View) holder.checkBox.getTag(1);
TextView shoppingitemTextview = (TextView) shoppingitemRow.findViewById(R.id.shoppingitem);
The TextView shoppingitemTextview is referencing to the actual row in the row layout view of the created list view for this shopping list app. You can edit now the textview (here the Textname of a shopping item) of the item of a row where its check box was clicked.
Add List View functionality to the main activity class "MainActivity.java"
Add this following code in the class "MainActivity":
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ListView;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
private ListView shoppingListView;
public static ArrayList<Shopping> shoppingListArray;
private ShoppingAdapter shoppingAdapter;
private String[] shoppingitemslist = new String[]{"Ice Cream", "Apple", "Chocolate", "Cheese", "Watermelon", "Salad"};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Create ListView
shoppingListView = (ListView) findViewById(R.id.shoppinglistview);
//Configure ListView
shoppingListArray = createAndGetShoppinglistModel(false);
shoppingAdapter = new ShoppingAdapter(this, this.shoppingListArray);
shoppingListView.setAdapter(this.shoppingAdapter);
}
/**
* Creates List of shopping item rows from defined String array "shoppingitemslist"
**/
private ArrayList<Shopping> createAndGetShoppinglistModel(boolean isSelect){
ArrayList<Shopping> shoppingList = new ArrayList<>();
for(int i = 0; i < 6; i++){
Shopping shopping = new Shopping();
shopping.setMarked(isSelect);
shopping.setShoppingItem(shoppingList[i]);
shoppingList.add(shopping);
}
return list;
}
}
The data for the ListView will be added in the function onCreate(), because the ListView will be displayed directly after the app was started. The ListView gets an Adapter (which is here the created "shoppingAdapter") which does manage the data (components, values in rows) of the list view.
Here the List Array "shoppingListArray" that contains the items of the shopping list, will be created from a defined String array "shoppingitemslist".
You can also extend the application to load data from a database. Saving and loading data from database in Android is mentioned in an other tutorial on this site, which you can find here:
https://ard-site.net/tutorials/android/room-database-app-to-save-data-in-a-database-format-more-easily
If you want to know more about the here used ListView or BaseAdapter, then please visit these sites:
More about ListView:
https://developer.android.com/reference/android/widget/ListView
More about BaseAdapter:
https://developer.android.com/reference/android/widget/BaseAdapter