Android list select all

Implement Android RecyclerView list of checkboxes with “select all” option — double tier!

Mar 16 · 4 min read

Creating a list of checkboxes isn’t a difficult mission. Adding a “select all” is arguably not too complicated as well.
But… what if we wanted to add subcategories? And… implement this in….. a recyclerView? Now this becomes a bit more complicated and confusing, and what is easier than finding a code that does exactly that with a simple explanation? So here we go…

Let’s start from the end, this is what we are trying to achieve:

A list of items, with sub categories and a “select all” option.

(Yeah, yeah, I know tomato is actually a fruit…)

Let ’ s define the row types so we are on the same page:

Here are the different scenarios we need to cover:

  1. If TopHeader is checked or unchecked => Update state of ALL the other items accordingly
  2. If CatHeader is checked or unchecked => Update state of the child items accordingly AND check if the TopHeader needs to be updated
  3. if a ProductRow is checked or unchecked => Check if CatHeader or TopHeader need to be updated

When would the parent need to be updated?

  1. If all it’s children are now checked , the parent must be checked as well
  2. If at least one of it’s children is unchecked, the parent must be unchecked

In this example we are passing a list of type RowModel, which includes the

  1. rowType
  2. productName for the product rows
  3. category — just a String in this example
  4. isChecked — which determines the state of the checkbox, so we can control a checkbox while computing (onBindViewHolder) a different row (holder)

[This is all simplified for the example, it probably makes more sense that the products and categories are objects]

Here is the list I created for the example:

The recyclerView is defined in mainActivity, where each row is a checkbox defined in row_layout.xml:

The adapter is where everything happens, let’s break it into pieces and see how we cover all the scenarios listed above.

[Again, this is simplified for the example, using different view types for the recyclerView is probably better practice]

In onBindViewHolder we set the text according to the view type in (holder.checkBox. text = … ) and add a few design lines, which I won’t elaborate on in this article.

Now, at the top we add:

If the data item isChecked == true , we check the UI checkbox accordingly, and if necessary, grey out lines that aren’t checked, which will look like this:

The setCheckboxTextColor method is implemented in the adapter:

Now it is time to set the listener:

The first two lines, common for any view type, change the data item for the current holder and the text color.

Now let’s look at each view type separately:

These lines change the “isChecked” data for all the other items in the list. In IndexList we keep the positions that need to be notified to update when calling notifyItemChanged( it).

Note: from experience, updating the table with notifyDataSetChanged() can cause issues as it will be updating the header again

So very similar to the top header code, we update all the children according to the father, but here we also filter on the category so we only change the correct items. After updating the children we need to see if the parent (top header in this case) must be updated as well, which is done in isAllItemsSameStatus() which we’ll get to soon

Читайте также:  Что лучше для работы ios или android что

Product row does not need to update any fellow rows, but might affect the top and category checkboxes which are implemented in isAllItemsSameStatus()

In order to update the headers we need 3 parameters:

  1. row: RowModel — the row data to be updated. For Top header it is always productList[0]. As to category row, we need to find it by calling:

2. isChecked: Boolean — the state of the checkbox to be updated. For Top header we check if the number of rows that are checked equal the number of rows in total (minus the top header):

For category row we do the same on the children only:

3. position: Int — to determine which holder needs to be update, for top header it is always row 0
For category holder we find it:

And finally update the header row:

Important! Checkboxes in recyclerView can cause issues, since the recyclerView, true to it’s name, recycles the views and the checkbox listener gets messed up. Therefore we add:

at the top, removing the listener that was already assigned to this holder. Be sure to add it before the checkbox is assigned.

And… That’s it! I hope this was clear, please ask post any questions in the comments and best of luck!

Источник

Using lists in Android wth ListView — Tutorial

This tutorial describes how to use ListView together with activities and fragments in Android.

1. Using lists in Android

The display of elements in a list is a very common pattern in mobile applications. The user sees a list of items and can scroll through them. Such an activity is depicted in the following picture.

Typically the user interacts with the list via the toolbar, for example, via a button which refreshes the list. Individual list items can be selected. This selection can update the toolbar or can trigger a detailed screen for the selection. The following graphic sketches that. On the selection of a list item another activity is started.

2. Android and the ListView widget

2.1. Views for handling lists

Android provides the ListView and the ExpandableListView classes which are capable of displaying a scrollable list of items. The ExpandableListView class supports a grouping of items.

2.2. Possible input types for lists

The input of a list (items in the list) can be arbitrary Java objects. The adapter extracts the correct data from the data object and assigns this data to the views in the row of the ListView .

These items are typically called the data model of the list. An adapter can receive data as input.

2.3. Adapters

An adapter manages the data model and adapts it to the individual entries in the widget. An adapter extends the BaseAdapter class.

Every line in the widget displaying the data consists of a layout which can be as complex as you want. A typical line in a list has an image on the left side and two text lines in the middle as depicted in the following graphic.

A layout file for such a line might look like the following.

The adapter would inflate the layout for each row in its getView() method and assign the data to the individual views in the row.

The adapter is assigned to the ListView via the setAdapter method on the ListView object.

Adapters are not only used by ListView , but also by other views which extend AdapterView as, for example, Spinner , GridView , Gallery and StackView .

2.4. Filtering and sorting

The filtering and sorting of the data is handled by the adapter. You need to implement the logic in your custom adapter implementation.

2.5. Data updates in the adapter

The notifyDataSetChanged() method on the adapter is called if the data has changed or if new data is available.

The notifyDataSetInvalidated() method is called if the data is not available anymore.

2.6. Listener

To react to selections in the list, set an OnItemClickListener to your ListView .

3. Default adapter

3.1. Default platform adapter

Android provides default adapter implementations; the most important are ArrayAdapter and CursorAdapter . ArrayAdapter can handle data based on Arrays or java.util.List . SimpleCursorAdapter can handle database related data.

3.2. Using ArrayAdapter

The ArrayAdapter class can handle a list or arrays of Java objects as input. Every Java object is mapped to one row. By default, it maps the toString() method of the object to a view in the row layout.

Читайте также:  Как с андроида отправить смайлик

You can define the ID of the view in the constructor of the ArrayAdapter otherwise the android.R.id.text1 ID is used as default.

The ArrayAdapter class allows to remove all elements in its underlying data structure with the clear() method call. You can then add new elements via the add() method or a Collection via the addAll() method.

You can also directly modify the underlying data structure and call the notifyDataSetChanged() method on the adapter to notify it about the changes in data.

If you want to change the data in your adapter, the underlying data structure must support this operation. This is, for example, the case for the ArrayList class, but not for arrays.

3.3. ListView example with ArrayAdapter

The following listing shows a layout file called activity_listviewexampleactivity.xml which includes a ListView .

The following example shows the usage of the ListView view in an activity. It uses a default layout from the Android platform for the row layout. It also demonstrates the removal of list items and uses animations for the removal.

4. Custom adapter implementations

4.1. Developing a custom adapter

The ArrayAdapter is limited as it supports only the mapping of toString() to one view in the row layout. To control the data assignment and to support several views, you have to create your custom adapter implementation.

For this you would extend an existing adapter implementation or subclass the BaseAdapter class directly.

Frequently you extend ArrayAdapter to write a custom adapter, as this is simpler than extending BaseAdapter directly.

4.2. Preparing a row for the list

The adapter needs to create a layout for each row of the list. The ListView instance calls the getView() method on the adapter for each data element. In this method the adapter creates the row layout and maps the data to the views in the layout.

This root of the layout is typically a ViewGroup (layout manager) and contains several other views, e.g., an ImageView and a TextView . The following graphic shows a list with different layouts for odd and even rows.

Within the getView() method you would inflate an XML based layout and then set the content of the individual views based on the Java object for this row. To inflate the XML layout file, you can use the LayoutInflator system service.

This layout inflator service can get accessed via the getLayoutInflator() method of the activity or via the context.getSystemService(Context.LAYOUT_INFLATER_SERVICE) method call.

After the adapter inflated the layout, it searches for the relevant views in the layout and fills them with the data. The individual elements in the layout can be found via the findViewById() method call on the top level view.

4.3. Example for a custom adapter

The following code shows an implementation of a custom adapter. This adapter assumes that you have two png files (no.png and ok.png) in one of your directory]]res/drawable folders. The coding inflates an XML layout file, finds the relevant views in the layout and sets their content based on the input data.

4.4. Updating the data model from the adapter

The row can also contain views which interact with the underlying data model via the adapter. For example, you can have a Checkbox in your row layout and if the Checkbox is selected, the underlying data is changed.

5. ListActivity and ListFragment

5.1. Default container for using ListView

Android provides specialized fragment and activity classes to simplify list handling.

The classes are the ListActivity class, if you want to use lists in activities, and the ListFragment class, if you want to use lists in fragments.

You do not have to assign a layout to these elements. If you do not define a layout, the activity or fragment contains a single ListView by default. ListActivity and ListFragment also allow you to override a onListItemClick() method for handling selection of list items.

Both classes allow you to set the adapter to the default ListView via the setListAdapter() method.

The following example code shows a simple ListFragment implementation.

The next example code demonstrates the usage of a ListActivity .

5.2. ListActivity and custom layout

You can use a custom layout with ListActivity or ListFragment . In this case the fragment or activity searches in the provided layout for a ListView with the predefined android:id attribute set to @android:id/list . This usage is demonstrated by the following code snippet.

If you do not use this ID or do not include a ListView into your layout, the application crashes once you try to display the activity or the fragment.
Читайте также:  Pajero 4 rockford android

5.3. Placeholder for an empty list

You can also use a view with the @android:id/empty ID in your layout. The corresponding activity and fragment shows this view automatically if the ListView is empty and hides it otherwise. For example, you could display an error message in such a view.

6. Exercise: Using ListView and ListActivity

The following exercise demonstrates how to use a ListView in an ListActivity . You use the predefined ArrayAdapter class and an existing Android layout for the rows.

Create a new Android project called de.vogella.android.listactivity with the activity called MyListActivity .

Change MyListActivity class based on the following code example. Note that the setContentView() method is not used.

7. Exercise: ListActivity with custom layout

In our example your will define your layout for the rows and use it in your adapter.

Create the rowlayout.xml layout file in the directory]]res/layout folder of the de.vogella.android.listactivity project.

Change your activity so that it uses the new layout.

8. Tutorial: Implementing your customer adapter

The following uses two images «no.png» and «ok.png». I placed them in the «res/drawable-mdpi» folder. You must create your own icons. In case you do not find any icons just copy «icon.png» and use a drawing program to change it a little bit and create a second one.

Create the class MySimpleArrayAdapter which will serve as our adapter.

To use this adapter, change the activity to the following.

If you run this example you should get a list with different icons for the certain elements.

9. ListViews and performance

9.1. Motivation

Performance is especially important on Android as users expect fast reaction times. Compared to desktop computers an Android device is relatively slow from the hardware perspective.

This part describes how to reduce these operations to implement your custom list adapter efficiently. The default Android adapters like ArrayAdapter are already performance optimized.

9.2. Time consuming operations

Every view which gets inflated from an XML layout file will result in a Java object. Inflating layouts and creating Java objects are expensive with regards to time and memory consumption.

In addition using the findViewById() method is relatively time consuming, even though it is not as bad as XML inflating.

9.3. Avoiding layout inflation and object creation

A ListView typically contains more data than the number of displayed rows. If the user scrolls the list, then the rows and their associated views will be scrolled out of the visible area. The Java objects which represent the rows can be reused for newly visible rows.

If Android determines that a row is not visible anymore, it allows the getView() of the adapter method to reuse the associated view via the convertView parameter.

The adapter can assign new data to the views contained in the view hierarchy of the convertView . This avoids inflating an XML file and creating new Java objects.

In case Android cannot reuse a row, the Android system passes null to the convertView parameter. Therefore the adapter implementation needs to check for this.

9.4. View holder pattern

A ViewHolder implementation allows to avoid the findViewById() method in an adapter.

A ViewHolder class is typically a static inner class in your adapter which holds references to the relevant views in your layout. This reference is assigned to the row view as a tag via the setTag() method.

If we receive a convertView object, we can get the instance of the ViewHolder via the getTag() method and assign the new attributes to the views via the ViewHolder reference.

While this sounds complex this is approximately 15 % faster than using the findViewById() method.

9.5. Example

The following code shows a performance optimized adapter implementation which reuses existing views and implements the holder pattern.

10. Storing the selection of a view

By default a ListView has no selection mode active. You can activate it via the setChoiceMode() method call. Pass ListView.CHOICE_MODE_MULTIPLE for multiple selections or ListView.CHOICE_MODE_SINGLE for single selections to this method.

To get the selected items of a ListView , use the getCheckedItemPosition() for a single selection method or listView.getCheckedItemPositions() for multiple selections. If you have stable ID, you could also use the getCheckedItemIds() method to get the selected IDs.

Android already provides a default layout for this: the android.R.layout.simple_list_item_multiple_choice layout which contains a configured CheckedTextView view.

The following activities demonstrate how to use these selection modes. If you use these modes, the ListView stores the selected values. It is not persisted in your data model.

Источник

Оцените статью