recycler view

9
RecyclerView Glossary of terms: Adapter: A subclass of RecyclerView.Adapter responsible for providing views that represent items in a data set. Position: The position of a data item within an Adapter . Index: The index of an attached child view as used in a call to getChildAt(int) . Contrast with Position. Binding: The process of preparing a child view to display data corresponding to a position within the adapter. Recycle (view): A view previously used to display data for a specific adapter posit be placed in a cache for later reuse to display the same type of data again later. This drastically improve performance by sipping initial layout inflation or construction. Scrap (view): A child view that has entered into a temporarily detached state durin layout. !crap views may be reused without becoming fully detached from the parent RecyclerView" either unmodified if no rebinding is re#uired or modified by the adapter view was considered dirty . Dirty (view): A child view that must be rebound by the adapter before being display Positions in RecyclerView: RecyclerView introduces an additional level of abstraction between the RecyclerView.Adapter andRecyclerView.LayoutManager to be able to detect data set changes in batches during a layout calculation. This saves $ayout%anager from tracing ad changes to calculate animations. &t also helps with performance because all view bindings happen at the same time and unnecessary bindings are avoided. 'or this reason" there are two types of position related methods in RecyclerView: layout position: (osition of an item in the latest layout calculation. This is the from the $ayout%anager)s perspective. adapter position: (osition of an item in the adapter. This is the position from the perspective.

Upload: vkm2013

Post on 03-Nov-2015

23 views

Category:

Documents


0 download

DESCRIPTION

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

TRANSCRIPT

RecyclerView

Glossary of terms: Adapter:A subclass ofRecyclerView.Adapterresponsible for providing views that represent items in a data set. Position:The position of a data item within anAdapter. Index:The index of an attached child view as used in a call togetChildAt(int). Contrast withPosition. Binding:The process of preparing a child view to display data corresponding to apositionwithin the adapter. Recycle (view):A view previously used to display data for a specific adapter position may be placed in a cache for later reuse to display the same type of data again later. This can drastically improve performance by skipping initial layout inflation or construction. Scrap (view):A child view that has entered into a temporarily detached state during layout. Scrap views may be reused without becoming fully detached from the parent RecyclerView, either unmodified if no rebinding is required or modified by the adapter if the view was considereddirty. Dirty (view):A child view that must be rebound by the adapter before being displayed.Positions in RecyclerView:RecyclerView introduces an additional level of abstraction between theRecyclerView.AdapterandRecyclerView.LayoutManagerto be able to detect data set changes in batches during a layout calculation. This saves LayoutManager from tracking adapter changes to calculate animations. It also helps with performance because all view bindings happen at the same time and unnecessary bindings are avoided.For this reason, there are two types ofpositionrelated methods in RecyclerView: layout position: Position of an item in the latest layout calculation. This is the position from the LayoutManager's perspective. adapter position: Position of an item in the adapter. This is the position from the Adapter's perspective.These two positions are the same except the time between dispatchingadapter.notify*events and calculating the updated layout.Methods that return or receive*LayoutPosition*use position as of the latest layout calculation (e.g.getLayoutPosition(),findViewHolderForLayoutPosition(int)). These positions include all changes until the last layout calculation. You can rely on these positions to be consistent with what user is currently seeing on the screen. For example, if you have a list of items on the screen and user asks for the 5thelement, you should use these methods as they'll match what user is seeing.The other set of position related methods are in the form of*AdapterPosition*. (e.g.getAdapterPosition(),findViewHolderForAdapterPosition(int)) You should use these methods when you need to work with up-to-date adapter positions even if they may not have been reflected to layout yet. For example, if you want to access the item in the adapter on a ViewHolder click, you should usegetAdapterPosition(). Beware that these methods may not be able to calculate adapter positions ifnotifyDataSetChanged()has been called and new layout has not yet been calculated. For this reasons, you should carefully handleNO_POSITIONornullresults from these methods.When writing aRecyclerView.LayoutManageryou almost always want to use layout positions whereas when writing anRecyclerView.Adapter, you probably want to use adapter positions.

Creating Lists and CardsTo create complex lists and cards with material design styles in your apps, you can use theRecyclerViewandCardViewwidgets.Create Lists

TheRecyclerViewwidget is a more advanced and flexible version ofListView. This widget is a container for displaying large data sets that can be scrolled very efficiently by maintaining a limited number of views. Use theRecyclerViewwidget when you have data collections whose elements change at runtime based on user action or network events.TheRecyclerViewclass simplifies the display and handling of large data sets by providing: Layout managers for positioning items Default animations for common item operations, such as removal or addition of itemsYou also have the flexibility to define custom layout managers and animations forRecyclerViewwidgets.

Figure 1. TheRecyclerViewwidget.To use theRecyclerViewwidget, you have to specify an adapter and a layout manager. To create an adapter, extend theRecyclerView.Adapterclass. The details of the implementation depend on the specifics of your dataset and the type of views. For more information, see theexamplesbelow.

Figure 2- Lists withRecyclerView.Alayout managerpositions item views inside aRecyclerViewand determines when to reuse item views that are no longer visible to the user. To reuse (orrecycle) 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 expensivefindViewById()lookups.RecyclerViewprovides these built-in layout managers: LinearLayoutManagershows items in a vertical or horizontal scrolling list. GridLayoutManagershows items in a grid. StaggeredGridLayoutManagershows items in a staggered grid.To create a custom layout manager, extend theRecyclerView.LayoutManagerclass.AnimationsAnimations for adding and removing items are enabled by default inRecyclerView. To customize these animations, extend theRecyclerView.ItemAnimatorclass and use theRecyclerView.setItemAnimator()method.ExamplesThe following code example demonstrates how to add theRecyclerViewto a layout:

Once you have added aRecyclerViewwidget 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:public class MyActivity extends Activity { private RecyclerView mRecyclerView; private RecyclerView.Adapter mAdapter; private RecyclerView.LayoutManager mLayoutManager;

@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.my_activity); mRecyclerView = (RecyclerView) findViewById(R.id.my_recycler_view);

// use this setting to improve performance if you know that changes // in content do not change the layout size of the RecyclerView mRecyclerView.setHasFixedSize(true);

// use a linear layout manager mLayoutManager = new LinearLayoutManager(this); mRecyclerView.setLayoutManager(mLayoutManager);

// specify an adapter (see also next example) mAdapter = new MyAdapter(myDataset); mRecyclerView.setAdapter(mAdapter); } ...}

The adapter provides access to the items in your data set, 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 usingTextViewwidgets:public class MyAdapter extends RecyclerView.Adapter { private String[] mDataset;

// 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 public static class ViewHolder extends RecyclerView.ViewHolder { // each data item is just a string in this case public TextView mTextView; public ViewHolder(TextView v) { super(v); mTextView = v; } }

// Provide a suitable constructor (depends on the kind of dataset) public MyAdapter(String[] myDataset) { mDataset = myDataset; }

// Create new views (invoked by the layout manager) @Override public MyAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { // create a new view View v = LayoutInflater.from(parent.getContext()) .inflate(R.layout.my_text_view, parent, false); // set the view's size, margins, paddings and layout parameters ... ViewHolder vh = new ViewHolder(v); return vh; }

// Replace the contents of a view (invoked by the layout manager) @Override public void onBindViewHolder(ViewHolder holder, int position) { // - get element from your dataset at this position // - replace the contents of the view with that element holder.mTextView.setText(mDataset[position]);

}

// Return the size of your dataset (invoked by the layout manager) @Override public int getItemCount() { return mDataset.length; }}

Figure 3. Card examples.Create Cards

CardViewextends theFrameLayoutclass and lets you show information inside cards that have a consistent look across the platform.CardViewwidgets can have shadows and rounded corners.To create a card with a shadow, use thecard_view:cardElevationattribute.CardViewuses real elevation and dynamic shadows on Android 5.0 (API level 21) and above and falls back to a programmatic shadow implementation on earlier versions. For more information, seeMaintaining Compatibility.Use these properties to customize the appearance of theCardViewwidget: To set the corner radius in your layouts, use thecard_view:cardCornerRadiusattribute. To set the corner radius in your code, use theCardView.setRadiusmethod. To set the background color of a card, use thecard_view:cardBackgroundColorattribute.The following code example shows you how to include aCardViewwidget in your layout:

For more information, see the API reference forCardView.Add Dependencies

TheRecyclerViewandCardViewwidgets are part of thev7 Support Libraries. To use these widgets in your project, add theseGradle dependenciesto your app's module:dependencies { ... compile 'com.android.support:cardview-v7:21.0.+' compile 'com.android.support:recyclerview-v7:21.0.+'}