Thursday, August 11, 2016

Android From Scratch: Understanding Adapters and Adapter Views_part 2 (end)


6. Adding Event Listeners

It is possible to listen for click and long click events on the items inside an adapter view. As an example, let's add a click event listener to the GridView.

Create a new instance of an anonymous class that implements the AdapterView.OnItemClickListener interface and pass it to the setOnItemClickListener() method of the GridView object. Android Studio automatically generates a stub for the onItemClick()) method of the interface. You'll notice that the method's parameters include an integer specifying the position of the list item. You can use this integer to find out which item in the data set the user clicked.

The following code illustrates how to display a simple message as a snackbar every time an item in the GridView is clicked.
  1. cheeseGrid.setOnItemClickListener(new AdapterView.OnItemClickListener() {
  2.     @Override
  3.     public void onItemClick(AdapterView<?> adapterView,
  4.                             View view, int position, long rowId) {
  5.  
  6.         // Generate a message based on the position
  7.         String message = "You clicked on " + cheeses[position];
  8.  
  9.         // Use the message to create a Snackbar
  10.         Snackbar.make(adapterView, message, Snackbar.LENGTH_LONG)
  11.                 .show(); // Show the Snackbar
  12.     }
  13. });
If you run the app and click any item in the grid, a message appears at the bottom of the screen. Note that you can use the same code to listen for click events on items inside a ListView.


7. Extending the ArrayAdapter

An ArrayAdapter can handle only one TextView widget inside the layout of the View objects it generates. To broaden its capabilities you must extend it. Before we do that, however, let's create a slightly more complex data set.

Instead of strings, let's say our data set contains objects of the following class:
  1. static class Cheese {
  2.     String name;
  3.     String description;
  4.  
  5.     public Cheese(String name, String description) {
  6.         this.name = name;
  7.         this.description = description;
  8.     }
  9. }
This is the data set we will be using:
  1. Cheese[] cheeses = {
  2.         new Cheese("Parmesan", "Hard, granular cheese"),
  3.         new Cheese("Ricotta", "Italian whey cheese"),
  4.         new Cheese("Fontina", "Italian cow's milk cheese"),
  5.         new Cheese("Mozzarella", "Southern Italian buffalo milk cheese"),
  6.         new Cheese("Cheddar", "Firm, cow's milk cheese"),
  7. };
As you can see, the Cheese class contains two fields, name and description. To display both fields in a lists or grid, the layout of the items must contain two TextView widgets.

Create a new layout XML file and name it custom_item.xml. Add a Large text and a Small text widget to it. Set the id attribute of the first widget to cheese_name and that of the second one to cheese_description. The contents of the layout XML file should now 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.     <TextView
  13.         android:layout_width="wrap_content"
  14.         android:layout_height="wrap_content"
  15.         android:textAppearance="?android:attr/textAppearanceSmall"
  16.         android:text="Small Text"
  17.         android:id="@+id/cheese_description" />
  18. </LinearLayout>
The ArrayAdapter must also be capable of handling two TextView widgets. Revisit your activity, create a new anonymous class that extends the ArrayAdapter class, and override its getView() method. Make sure that you pass the array as an argument to its constructor.
  1. ArrayAdapter<Cheese> cheeseAdapter = 
  2.         new ArrayAdapter<Cheese>(this, 0, cheeses) {
  3.             @Override
  4.             public View getView(int position,
  5.                                 View convertView,
  6.                                 ViewGroup parent) {
  7.             }
  8.         };
Inside the getView() method, you must use the position parameter as an index of the array and fetch the item at that index.
  1. Cheese currentCheese = cheeses[position];
The second parameter of the getView() method is what enables us to reuse View objects. If you ignore it, the performance of your adapter view will be poor. When the getView() method is called for the first time, convertView is null. You must initialize it by inflating the resource file that specifies the layout of the list items. To do so, obtain a reference to a LayoutInflater using the getLayoutInflater() method and invoke its inflate() method.
  1. // Inflate only once
  2. if(convertView == null) {
  3.     convertView = getLayoutInflater()
  4.                     .inflate(R.layout.custom_item, null, false);
  5. }
At this point, you can use findViewById() to get a reference to the TextView widgets inside the layout and call their setText() methods to initialize them using data from the array.
  1. TextView cheeseName = 
  2.     (TextView)convertView.findViewById(R.id.cheese_name);
  3. TextView cheeseDescription = 
  4.     (TextView)convertView.findViewById(R.id.cheese_description);
  5. cheeseName.setText(currentCheese.name);
  6. cheeseDescription.setText(currentCheese.description);
Finally, return convertView so that it can be used to populate any adapter view associated with the adapter.
  1. return convertView;
8. Using a View Holder

The getView() method is called repeatedly by the adapter view to populate itself. Therefore, you must try to minimize the number of operations you perform in it.

In the previous step, you might have noticed that, even though we made sure that the layout of the list items is inflated only once, the findViewById() method, which consumes many CPU cycles, is called every time the getView() method is called.

To avoid this and to improve the performance of the adapter view, we need to store the results of the findViewById( method inside the convertView object. To do so, we can use a view holder object, which is nothing more than an object of a class that can store the widgets present in the layout.

Because the layout has two TextView widgets, the view holder class must also have two TextView widgets. I have named the class ViewHolder.
  1. static class ViewHolder{
  2.     TextView cheeseName;
  3.     TextView cheeseDescription;
  4. }
In the getView() method, after you inflate the layout, you can now initialize the view holder object using the findViewById() method.
  1. ViewHolder viewHolder = new ViewHolder();
  2. viewHolder.cheeseName =
  3.         (TextView)convertView.findViewById(R.id.cheese_name);
  4. viewHolder.cheeseDescription =
  5.         (TextView)convertView.findViewById(R.id.cheese_description);
To store the view holder object in convertView, use its setTag() method.
  1. // Store results of findViewById
  2. convertView.setTag(viewHolder);
And now, every time getView() is called, you can retrieve the view holder object from convertView using the getTag() method and update the TextView widgets inside it using their setText() methods.
  1. TextView cheeseName = 
  2.     ((ViewHolder)convertView.getTag()).cheeseName;
  3. TextView cheeseDescription = 
  4.     ((ViewHolder)convertView.getTag()).cheeseDescription;     
  5. cheeseName.setText(currentCheese.name);
  6. cheeseDescription.setText(currentCheese.description);
If you run your app now, you can see the GridView displaying two lines of text in each cell.


Conclusion

In this tutorial, you learned how to create an adapter and use it to populate various adapter views. You also learned how to create your own custom adapter. Although we only focused on the ArrayAdapterListView, and GridView classes, you can use the same techniques for other adapters and adapter views the Android SDK offers.

The Android Support Library includes the RecyclerView class. It behaves much like an adapter view, but it isn't a subclass of the AdapterView class. You should consider using it if you want to create more complex lists, especially ones that use multiple layout files for their items.
Written by Ashraff Hathibelagal

If you found this post interesting, follow and support us.
Suggest for you:

Android: From Beginner to Paid Professional

The Complete Android Developer Course - Build 14 Apps

Python For Android Hacking Crash Course: Trojan Perspective

No comments:

Post a Comment