본문 바로가기
개발/Adroid

[android studio] RecyclerView

by KEI NETWORK 2019. 8. 16.
728x90

If your app needs to display a scrolling list of elements based on large data sets (or data that frequently changes), you should use RecyclerView as described on this page.

Tip: Start with some template code in Android Studio by clicking File > New > Fragment > Fragment (List). Then simply add the fragment to your activity layout.

Figure 1. A list using RecyclerView

Figure 2. A list also using CardView

If you'd like to create a list with cards, as shown in figure 2, also use the CardView widget as described in Create a Card-based Layout.

If you'd like to see some sample code for RecyclerView, check out the RecyclerView Sample App.

RecyclerView overview

The RecyclerView widget is a more advanced and flexible version of ListView.

In the RecyclerView model, several different components work together to display your data. The overall container for your user interface is a RecyclerView object that you add to your layout. The RecyclerView fills itself with views provided by a layout manager that you provide. You can use one of our standard layout managers (such as LinearLayoutManager or GridLayoutManager), or implement your own.

The views in the list are represented by view holder objects. These objects are instances of a class you define by extending RecyclerView.ViewHolder. Each view holder is in charge of displaying a single item with a view. For example, if your list shows music collection, each view holder might represent a single album. The RecyclerView creates only as many view holders as are needed to display the on-screen portion of the dynamic content, plus a few extra. As the user scrolls through the list, the RecyclerView takes the off-screen views and rebinds them to the data which is scrolling onto the screen.

The view holder objects are managed by an adapter, which you create by extending RecyclerView.Adapter. The adapter creates view holders as needed. The adapter also binds the view holders to their data. It does this by assigning the view holder to a position, and calling the adapter's onBindViewHolder() method. That method uses the view holder's position to determine what the contents should be, based on its list position.

This RecyclerView model does a lot of optimization work so you don't have to:

  • When the list is first populated, it creates and binds some view holders on either side of the list. For example, if the view is displaying list positions 0 through 9, the RecyclerView creates and binds those view holders, and might also create and bind the view holder for position 10. That way, if the user scrolls the list, the next element is ready to display.
  • As the user scrolls the list, the RecyclerView creates new view holders as necessary. It also saves the view holders which have scrolled off-screen, so they can be reused. If the user switches the direction they were scrolling, the view holders which were scrolled off the screen can be brought right back. On the other hand, if the user keeps scrolling in the same direction, the view holders which have been off-screen the longest can be re-bound to new data. The view holder does not need to be created or have its view inflated; instead, the app just updates the view's contents to match the new item it was bound to.
  • When the displayed items change, you can notify the adapter by calling an appropriate RecyclerView.Adapter.notify…() method. The adapter's built-in code then rebinds just the affected items.

Add the support library

To access the RecyclerView widget, you need to add the v7 Support Libraries to your project as follows:

  1. Open the build.gradle file for your app module.
  2. Add the support library to the dependencies section.dependencies {
        implementation
    'com.android.support:recyclerview-v7:28.0.0'
    }

     

Add RecyclerView to your layout

Now you can add the RecyclerView to your layout file. For example, the following layout uses RecyclerView as the only view for the whole layout:

<?xml version="1.0" encoding="utf-8"?>
<!-- A RecyclerView with some commonly used attributes -->
<android.support.v7.widget.RecyclerView
   
android:id="@+id/my_recycler_view"
   
android:scrollbars="vertical"
   
android:layout_width="match_parent"
   
android:layout_height="match_parent"/>

 

Once you have added a RecyclerView widget to your layout, obtain a handle to the object, connect it to a layout manager, and attach an adapter for the data to be displayed:

KOTLINJAVA

class MyActivity : Activity() {
   
private lateinit var recyclerView: RecyclerView
   
private lateinit var viewAdapter: RecyclerView.Adapter<*>
   
private lateinit var viewManager: RecyclerView.LayoutManager

   
override fun onCreate(savedInstanceState: Bundle?) {
       
super.onCreate(savedInstanceState)
        setContentView
(R.layout.my_activity)

        viewManager
= LinearLayoutManager(this)
        viewAdapter
= MyAdapter(myDataset)

        recyclerView
= findViewById<RecyclerView>(R.id.my_recycler_view).apply {
           
// use this setting to improve performance if you know that changes
           
// in content do not change the layout size of the RecyclerView
            setHasFixedSize
(true)

           
// use a linear layout manager
            layoutManager
= viewManager

           
// specify an viewAdapter (see also next example)
            adapter
= viewAdapter

       
}
   
}
   
// ...
}

 

Add a list adapter

To feed all your data to the list, you must extend the RecyclerView.Adapter class. This object creates views for items, and replaces the content of some of the views with new data items when the original item is no longer visible.

The following code example shows a simple implementation for a data set that consists of an array of strings displayed using TextView widgets:

KOTLINJAVA

class MyAdapter(private val myDataset: Array<String>) :
       
RecyclerView.Adapter<MyAdapter.MyViewHolder>() {

   
// Provide a reference to the views for each data item
   
// Complex data items may need more than one view per item, and
   
// you provide access to all the views for a data item in a view holder.
   
// Each data item is just a string in this case that is shown in a TextView.
   
class MyViewHolder(val textView: TextView) : RecyclerView.ViewHolder(textView)


   
// Create new views (invoked by the layout manager)
   
override fun onCreateViewHolder(parent: ViewGroup,
                                    viewType
: Int): MyAdapter.MyViewHolder {
       
// create a new view
       
val textView = LayoutInflater.from(parent.context)
               
.inflate(R.layout.my_text_view, parent, false) as TextView
       
// set the view's size, margins, paddings and layout parameters
       
...
       
return MyViewHolder(textView)
   
}

   
// Replace the contents of a view (invoked by the layout manager)
   
override fun onBindViewHolder(holder: MyViewHolder, position: Int) {
       
// - get element from your dataset at this position
       
// - replace the contents of the view with that element
        holder
.textView.text = myDataset[position]
   
}

   
// Return the size of your dataset (invoked by the layout manager)
   
override fun getItemCount() = myDataset.size
}

 

The layout manager calls the adapter's onCreateViewHolder() method. That method needs to construct a RecyclerView.ViewHolder and set the view it uses to display its contents. The type of the ViewHolder must match the type declared in the Adapter class signature. Typically, it would set the view by inflating an XML layout file. Because the view holder is not yet assigned to any particular data, the method does not actually set the view's contents.

The layout manager then binds the view holder to its data. It does this by calling the adapter's onBindViewHolder() method, and passing the view holder's position in the RecyclerView. The onBindViewHolder() method needs to fetch the appropriate data, and use it to fill in the view holder's layout. For example, if the RecyclerView is displaying a list of names, the method might find the appropriate name in the list, and fill in the view holder's TextView widget.

If the list needs an update, call a notification method on the RecyclerView.Adapter object, such asnotifyItemChanged(). The layout manager then rebinds any affected view holders, allowing their data to be updated.

Tip: You might find the ListAdapter class useful for determining which items in your list need to be updated when the list changes.

Customize your RecyclerView

You can customize the RecyclerView objects to meet your specific needs. The standard classes provide all the functionality that most developers will need; in many cases, the only customization you need to do is design the view for each view holder and write the code to update those views with the appropriate data. However, if your app has specific requirements, you can modify the standard behavior in a number of ways. The following sections describe some of the other common customizations.

Modifying the layout

The RecyclerView uses a layout manager to position the individual items on the screen and determine when to reuse item views that are no longer visible to the user. To reuse (or recycle) a view, a layout manager may ask the adapter to replace the contents of the view with a different element from the dataset. Recycling views in this manner improves performance by avoiding the creation of unnecessary views or performing expensive findViewById() lookups. The Android Support Library includes three standard layout managers, each of which offers many customization options:

  • LinearLayoutManager arranges the items in a one-dimensional list. Using a RecyclerView with LinearLayoutManager provides functionality like the older ListView layout.
  • GridLayoutManager arranges the items in a two-dimensional grid, like the squares on a checkerboard. Using a RecyclerView with GridLayoutManager provides functionality like the older GridView layout.
  • StaggeredGridLayoutManager arranges the items in a two-dimensional grid, with each column slightly offset from the one before, like the stars in an American flag.

If none of these layout managers suits your needs, you can create your own by extending the RecyclerView.LayoutManager abstract class.

Add item animations

Whenever an item changes, the RecyclerView uses an animator to change its appearance. This animator is an object that extends the abstract RecyclerView.ItemAnimator class. By default, the RecyclerView uses DefaultItemAnimator to provide the animation. If you want to provide custom animations, you can define your own animator object by extending RecyclerView.ItemAnimator.

Enable list-item selection

The recyclerview-selection library enables users to select items in RecyclerView list using touch or mouse input. You retain control over the visual presentation of a selected item. You can also retain control over policies controlling selection behavior, such as items that can be eligible for selection, and how many items can be selected.

To add selection support to a RecyclerView instance, follow these steps:

    1. Determine which selection key type to use, then build a ItemKeyProvider.

      There are three key types that you can use to identify selected items: Parcelable (and all subclasses likeUri), String, and Long. For detailed information about selection-key types, seeSelectionTracker.Builder.

    2. Implement ItemDetailsLookup.

ItemDetailsLookup enables the selection library to access information about RecyclerView items given a MotionEvent. It is effectively a factory for ItemDetails instances that are backed up by (or extracted from) a RecyclerView.ViewHolder instance.

    1. Update item Views in RecyclerView to reflect that the user has selected or unselected it.

      The selection library does not provide a default visual decoration for the selected items. You must provide this when you implement onBindViewHolder(). The recommended approach is as follows:

      • In onBindViewHolder(), call setActivated() (not setSelected()) on the View object with true or false (depending on if the item is selected).
      • Update the styling of the view to represent the activated status. We recommend you use a color state list resource to configure the styling.
    2. Use ActionMode to provide the user with tools to perform an action on the selection.

Register a SelectionTracker.SelectionObserver to be notified when selection changes. When a selection is first created, start ActionMode to represent this to the user, and provide selection-specific actions. For example, you may add a delete button to the ActionMode bar, and connect the back arrow on the bar to clear the selection. When the selection becomes empty (if the user cleared the selection the last time), don't forget to terminate action mode.

    1. Perform any interpreted secondary actions

At the end of the event processing pipeline, the library may determine that the user is attempting to activate an item by tapping it, or is attempting to drag and drop an item or set of selected items. React to these interpretations by registering the appropriate listener. For more information, seeSelectionTracker.Builder.

    1. Assemble everything with SelectionTracker.Builder

The following example shows how to put these pieces together by using the Long selection key:

KOTLINJAVA

var tracker = SelectionTracker.Builder(
   
"my-selection-id",
    recyclerView
,
   
StableIdKeyProvider(recyclerView),
   
MyDetailsLookup(recyclerView),
   
StorageStrategy.createLongStorage())
       
.withOnItemActivatedListener(myItemActivatedListener)
       
.build()

 

In order to build a SelectionTracker instance, your app must supply the same RecyclerView.Adapterthat you used to initialize RecyclerView to SelectionTracker.Builder. For this reason, you will most likely need to inject the SelectionTracker instance, once created, into your RecyclerView.Adapterafter the RecyclerView.Adapter is created. Otherwise, you won't be able to check an item's selected status from the onBindViewHolder() method.

    1. Include selection in the activity lifecycle events.

In order to preserve selection state across the activity lifecycle events, your app must call the selection tracker's onSaveInstanceState() and onRestoreInstanceState() methods from the activity'sonSaveInstanceState() and onRestoreInstanceState() methods respectively. Your app must also supply a unique selection ID to the SelectionTracker.Builder constructor. This ID is required because an activity or a fragment may have more than one distinct, selectable list, all of which need to be persisted in their saved state.

728x90

댓글