Android ListView

Android ListView

Android ListView – in previous tutorial we discussed about Android ReclyerView But in this tutorial we will discuss about Android ListView, so let’s start our tutorial.

Android ListView Introduction

This post will walk you through building simple and custom-made ListView in Android using different Android adapters.

Scrollview is well suited for displays where scrolling is necessary, but it isn’t reliable when scroll view is employed to render a more substantial data place. Instead you may use customized adapter views like ListView, GridView and Recycler View (Introduced in Android Lollipop) for long lists.

android listview

Android ListView can be an Android ViewGroup, used thoroughly to show the assortment of data in vertical scrollable rows. The list items are automatically placed to the list using an Adapter and Adapter pulls data from databases source such as a wide range, cursor, etc.

Android Adapter

Adapter is works as a bridge between databases and adapter views such as ListView, GridView. Adapter iterates through the info set from starting till the finish and generate Views for every single item in the list.

Android SDK provides three different Adapter execution, which includes ArrayAdapter, CursorAdapter and SimpleAdapter. An ArrayAdapter desires a wide range or an List as source, while CursorAdapter accepts the example of Cursor and SimpleAdapter maps the static data described in the resources. The sort of adapter that suits your app need is strictly predicated on the type data type.

The BaseAdapter is the universal implementation for all the three adapter types and can be utilized for ListView, GridView or for Spinners.

You may immediately use ArrayAdapter by moving array as suggestions or create your own custom-made class by extending BaseAdapter.

android listview

The image above, provides notion of customizable list views can be carried out using adapters.

 Android ListView Using ArrayAdapter

The easiest way for building list view is to apply ArrayAdapter. Pursuing are a few of the steps used to apply simple ListView using array adapter.

1.First step towards building list view is to recognize the type data, that you want to show in list. On this example, we are by using a static selection of strings.

2.Secondly, why don’t we declare list view in activity structure. Inside our example, the experience layout includes a list view inside linear structure. Provide android:identification=”@+identification/months_list” as ListView id.

3.Now finally, why don’t we instantiate the  the ArrayAdapter and arranged to ListView by calling setAdapter() method.

Pursuing code snippet depicts the list view declaration inside activity layout

<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:id="@+id/months_list"
    android:layout_width="match_parent"
    android:layout_height="wrap_content" >
  </ListView>
</LinearLayout>

 

Now instantiate the ListView and Array adapter. Pursuing code snippet depicts the experience code.

ListActivity.java

ListActivity.java

import android.os.Bundle;
import android.app.Activity;
import android.widget.ArrayAdapter;
import android.widget.ListView;

public class ListActivity extends Activity {
  private String[] monthsArray = { "JAN", "FEB", "MAR", "APR", "MAY", "JUNE", "JULY",
 "AUG", "SEPT", "OCT", "NOV", "DEC" };

  private ListView monthsListView;
  private ArrayAdapter arrayAdapter;

  /** Called when the activity is first created. */
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_list);

    monthsListView = (ListView) findViewById(R.id.months_list);

    // this-The current activity context.
    // Second param is the resource Id for list layout row item
    // Third param is input array 
    arrayAdapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, monthsArray);
    monthsListView.setAdapter(arrayAdapter);
  }
}

 

Output of the above mentioned code is really as follows

android listview

Android ListView Using Custom Adapter

So far we’ve created a straightforward list view using ArrayAdapter. Now it period to create something elegant custom a list by extending BaseAdapter. Pursuing steps are being used to implement custom-made ListView:

1.First step towards building custom list is to recognize the info model for each and every row. Inside our example we will screen set of NewsItem objects.

2.Secondly, why don’t we declare list view in activity design.

3.Now declare the design for every single row item.

4.Create your custom adapter category by extending BaseAdapter class.

5.Finally, why don’t we instantiate your custom adapter and arranged to ListView by calling setAdapter() method.

The NewsItem thing will symbolize each row in list. Declare NewsItem.java course and add the next code snippets.

public class NewsItem {
  private String headline;
  private String reporterName;
  private String date;
  public String getHeadline() {
    return headline;
  }

  public void setHeadline(String headline) {
    this.headline = headline;
  }

  public String getReporterName() {
    return reporterName;
  }

  public void setReporterName(String reporterName) {
    this.reporterName = reporterName;
  }

  public String getDate() {
    return date;
  }

  public void setDate(String date) {
    this.date = date;
  }
}

 Define Android List Row Layout

Why don’t we create a fresh custom structure for list view row item made up of headline, name and day TextView.

list_row_structure.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    android:padding="5dip" >

    <TextView
        android:id="@+id/title"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textStyle="bold"
        android:typeface="sans" />

    <TextView
        android:id="@+id/reporter"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/title"
        android:layout_marginTop="5dip"
        android:textColor="#343434"
        android:textSize="12sp" />

    <TextView
        android:id="@+id/date"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBaseline="@+id/reporter"
        android:layout_alignBottom="@+id/reporter"
        android:layout_alignParentRight="true"
        android:textColor="#343434"
        android:textSize="12sp" />
</RelativeLayout>

 

Android Custom List Adapter

Why don’t we create a fresh class known as CustomListAdapter.java, and prolong it from BaseAdapter. You need to override  the next methods form BaseAdpter class.

getCount()          This technique returns the full total volume of row matters for the listview. Typically this provides the size of the list you transferring as input.

getItem()            Returns subject representing data for every single row.

getItemId()        This returns the initial integer id that signifies each row item. Why don’t we come back the integer position value.

getView()            The getView() method profits a view example that represents an individual row in ListView item. Here you can inflate your own structure and update worth on list row.

Checkout the  pursuing code snippets for CustomListAdapter class.


Do You Have Any Question About This Tutorial? Ask Question Now On Andro Development & Get Answer Instantly. No Signup/Login Needed


public class CustomListAdapter extends BaseAdapter {
  private ArrayList<NewsItem> listData;
  private LayoutInflater layoutInflater;

  public CustomListAdapter(Context aContext, ArrayList<NewsItem> listData) {
    this.listData = listData;
    layoutInflater = LayoutInflater.from(aContext);
  }

  @Override
  public int getCount() {
    return listData.size();
  }

  @Override
  public Object getItem(int position) {
    return listData.get(position);
  }

  @Override
  public long getItemId(int position) {
    return position;
  }

  public View getView(int position, View convertView, ViewGroup parent) {
    ViewHolder holder;
    if (convertView == null) {
      convertView = layoutInflater.inflate(R.layout.list_row_layout, null);
      holder = new ViewHolder();
      holder.headlineView = (TextView) convertView.findViewById(R.id.title);
      holder.reporterNameView = (TextView) convertView.findViewById(R.id.reporter);
      holder.reportedDateView = (TextView) convertView.findViewById(R.id.date);
      convertView.setTag(holder);
    } else {
      holder = (ViewHolder) convertView.getTag();
    }

    holder.headlineView.setText(listData.get(position).getHeadline());
    holder.reporterNameView.setText("By, " + listData.get(position).getReporterName());
    holder.reportedDateView.setText(listData.get(position).getDate());
    return convertView;
  }

  static class ViewHolder {
    TextView headlineView;
    TextView reporterNameView;
    TextView reportedDateView;
  }
}

 

Declaring Android  ListView Layout

Declare Android ListView in your activity design.

<?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" >

    <ListView
        android:id="@+id/custom_list"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:dividerHeight="1dp" />

</LinearLayout>

 

Hooking UP to Activity

Well, our work is almost ready. Why don’t we put most of them alongside one another and connect it up to the experience. Pursuing code snippet depicts the experience category (MainActivity.java), where we initialize Adapter and connect it up to Android ListView.

public class MainActivity extends Activity {

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

    ArrayList image_details = getListData();
    final ListView lv1 = (ListView) findViewById(R.id.custom_list);
    lv1.setAdapter(new CustomListAdapter(this, image_details));
    lv1.setOnItemClickListener(new OnItemClickListener() {

      @Override
      public void onItemClick(AdapterView<?> a, View v, int position, long id) {
        Object o = lv1.getItemAtPosition(position);
        NewsItem newsData = (NewsItem) o;
        Toast.makeText(MainActivity.this, "Selected :" + " " + newsData, Toast.LENGTH_LONG).show();
      }
    });
  }

  private ArrayList getListData() {
    ArrayList<NewsItem> results = new ArrayList<NewsItem>();
    NewsItem newsData = new NewsItem();
    newsData.setHeadline("Dance of Democracy");
    newsData.setReporterName("Pankaj Gupta");
    newsData.setDate("May 26, 2013, 13:35");
    results.add(newsData);

                // Add some more dummy data for testing
    return results;
  }
}

 

This is actually the output of the above mentioned example.

android listview

Styling Android ListView

Like any other view, ListView in Android can custom-made by color, qualifications, selection color, etc. With this portion of tutorial, we will understand how to customise an Android ListView.

Changing Android ListView Selection Color

Android ListView default selection color can be evolved using selectors. Selectors permits to choose how list row will visually be represented predicated on different states. Why don’t we change the backdrop and content material color while list row is pressed state.

Create a fresh file known as list_color_selector.xml within your drawable folder and paste the next code snippets. This selector style will be utilized to change the backdrop color when list row is pressed.

<selector xmlns:android="http://schemas.android.com/apk/res/android">
     <!-- Normal state. -->
    <item android:drawable="@color/list_row_default_bg" 
        android:state_pressed="false" 
        android:state_selected="false"/>
    <!-- pressed state. -->
    <item android:drawable="@color/list_row_pressed_bg" 
        android:state_pressed="true"/>
    <!-- Selected state. -->
    <item android:drawable="@color/list_row_selected_bg" 
        android:state_pressed="false" 
        android:state_selected="true"/>

</selector>

 

Now, why don’t we create data file and called it as list_item_wording_selector.xml. This style will be utilized to change the written text color while list row is pressed.

<?xml version="1.0" encoding="UTF-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_pressed="true" android:color="@color/text_color_inverse" />
    <item android:state_focused="true" android:color="@color/text_color_inverse" />
    <item android:color="@color/text_color_default" />
</selector>

 

Define the next colors inside colors.xml record. Unless you have colors.xml data file already than create one inside worth folder and paste the next code snippets.

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="text_color_default">#00000C</color>
    <color name="text_color_inverse">#FFFFFF</color>
    <color name="white">#FFFFFF</color>
    <color name="list_row_default_bg">#ffffff</color>
    <color name="list_row_pressed_bg">#008cef</color>
    <color name="list_row_selected_bg">#86d3f6</color>
</resources>

 

Now why don’t we apply the list selector styles to ListView inside activity_main.xml file

<ListView
        android:id="@+id/custom_list"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:listSelector="@drawable/list_color_selector"
        android:dividerHeight="1dp" />

 

Now, we can apply the styles to word in “list_row_layout.xml”. Change all TextView widget textColor feature as shown below

TextView
        android:id="@+id/title"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text=""
        android:textColor="@drawable/list_item_text_selector"
        android:textStyle="bold"
        android:typeface="sans" />

 

output

android listview

ListView Divider Style

You should use the next properties to improve the list divider styles

The android:divider property is employed to create the list divider color. It accepts the colour in #RRGGBBAA format. In addition, it accepts mention of the drawable, which is shown as list drawable.

The android:dividerHeight property used to create the elevation of list divider. It could be described in dp.

<ListView
        android:id="@+id/custom_list"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:divider="#FF0000"
        android:dividerHeight="1dp"
        android:listSelector="@drawable/list_selector_flatcolor" />

 

Changing List Divider Pragmatically

You can even change the list view divider style programmatically form java code using setDivider() method.

ListView listView = getListView();
ColorDrawable devidrColor = new ColorDrawable(
      this.getResources().getColor(R.color.devidrColor));
listView.setDivider(devidrColor);
listView.setDividerHeight(1);

android listview

Here Our Tutorial Ends! 🙂

See Also:

Android RecyclerView

Android CardView

Android RelativeLayout

 


Do You Have Any Question About This Tutorial? Ask Question Now On Andro Development & Get Answer Instantly. No Signup/Login Needed