Monday, August 8, 2016

Android From Scratch: Understanding Adapters and Adapter Views_part1



Adapter views are so ubiquitous that you'd have a hard time finding a popular Android app that doesn't use them. The name might sound unfamiliar, but if you think you've never seen an adapter view, you are probably wrong. Every time you see an Android app display user interface elements in the form of a list, a grid, or a stack, you're seeing an adapter view in action.

An adapter view, as its name suggests, is a View object. This means, you can add it to your activities the same way you add any other user interface widget. However, it is incapable of displaying any data on its own. Its contents are always determined by another object, an adapter. In this tutorial, I show you how to create adapters and use them to feed different types of adapter views such as ListView and GridView.

1. What Is an Adapter?

An adapter is an object of a class that implements the Adapter interface. It acts as a link between a data set and an adapter view, an object of a class that extends the abstract AdapterView class. The data set can be anything that presents data in a structured manner. Arrays, List objects, and Cursor objects are commonly used data sets.

An adapter is responsible for retrieving data from the data set and for generating View objects based on that data. The generated View objects are then used to populate any adapter view that is bound to the adapter.

You can create your own adapter classes from scratch, but most developers choose to use or extend adapter classes provided by the Android SDK, such as ArrayAdapter and SimpleCursorAdapter. In this tutorial, we focus on the ArrayAdapter class.

2. How Do Adapter Views Work?

Adapter views can display large data sets very efficiently. For instance, the ListView and GridView widgets can display millions of items without any noticeable lag while keeping memory and CPU usage very low. How do they do that? Different adapter views follow different strategies. However, here's what most of them usually do.
  • They render only those View objects that are either already on-screen or that are about to move on-screen. This way, the memory consumed by an adapter view can be constant and independent of the size of the data set.
  • They also allow developers to minimize expensive layout inflate operations and recycle existing View objects that have move off-screen. This keeps CPU consumption low.
3. Creating an ArrayAdapter

To create an adapter, you need the following:
  • a data set
  • a resource file containing the layout of the generated View objects
Additionally, because the ArrayAdapter class can only work with strings, you need to make sure the layout of the generated View objects contains at least one TextView widget.

Step 1: Create the Data Set
The ArrayAdapter class can use both arrays and List objects as data sets. For now, let's use an array as the data set.
  1. String[] cheeses = {
  2.             "Parmesan",
  3.             "Ricotta",
  4.             "Fontina",
  5.             "Mozzarella",
  6.             "Cheddar"
  7.           };
Step 2: Create the Resource File
Create a new layout XML file whose root element is a LinearLayout and name it item.xml. Drag and drop a Large text widget in it and set the value of its id attribute to cheese_name. The layout XML file should look like this:
  1. <?xml version="1.0" encoding="utf-8"?>
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  3.     android:orientation="vertical" android:layout_width="match_parent"
  4.     android:layout_height="match_parent"
  5.     android:padding="@dimen/activity_horizontal_margin">
  6.     <TextView
  7.         android:layout_width="wrap_content"
  8.         android:layout_height="wrap_content"
  9.         android:textAppearance="?android:attr/textAppearanceLarge"
  10.         android:text="Large Text"
  11.         android:id="@+id/cheese_name" />
  12. </LinearLayout>
Step 3: Create the Adapter
In your activity, create a new instance of the ArrayAdapter class using its constructor. As its arguments, pass the name of the resource file, the identifier of the TextView, and a reference to the array. The adapter is now ready.
  1. ArrayAdapter<String> cheeseAdapter = 
  2.     new ArrayAdapter<String>(this,
  3.         R.layout.item,
  4.         R.id.cheese_name,
  5.         cheeses
  6.     );
4. Creating a List

To display a vertically scrollable list of items, you can use the ListView widget. To add the widget to your activity, you can either drag and drop it inside the activity's layout XML file or create it using its constructor in your Java code. For now, let's do the latter.
  1. ListView cheeseList = new ListView(this);
Usually, no other user interface widgets are placed inside a layout that contains a ListView. Therefore, pass the ListView to the setContentView() method of your activity so that it takes up the entire screen.
  1. setContentView(cheeseList);
To bind the ListView to the adapter we created in the previous step, call the setAdapter() method as shown below.
  1. cheeseList.setAdapter(cheeseAdapter);
If you run your app now, you should be able to see the contents of the array in the form of a list.

5. Creating a Grid

To display a vertically scrollable two-dimensional grid of items, you can use the GridView widget. Both ListView and GridView are subclasses of the abstract AbsListView class and they share many similarities. Therefore, if you know how to use one, you know how to use the other as well.

Use the constructor of the GridView class to create a new instance and pass it to the setContentView() method of your activity.
  1. GridView cheeseGrid = new GridView(this);
  2. setContentView(cheeseGrid);
To set the number of columns in the grid, call its setNumColumns() method. I'm going to make this a two-column grid.
  1. cheeseGrid.setNumColumns(2);
Usually, you'd want to adjust the width of the columns and the spacing between them using the setColumnWidth()setVerticalSpacing(), and setHorizontalSpacing() methods. Note that these methods use pixels as their units.
  1. cheeseGrid.setColumnWidth(60);
  2. cheeseGrid.setVerticalSpacing(20);
  3. cheeseGrid.setHorizontalSpacing(20);
You can now bind the GridView to the adapter we created earlier using the setAdapter() method.
  1. cheeseGrid.setAdapter(cheeseAdapter);
Run your app again to see what the GridView looks like.

Written by Ashraff Hathibelagal
If you found this post interesting, follow and support us.
Suggest for you:

No comments:

Post a Comment