Upload
francesco-azzola
View
480
Download
0
Embed Size (px)
Citation preview
Topics covered
RecyclerViewRecyclerViewCardViewCardViewAndroid adapterAndroid adapter
Home » android » cardview » java » recyclerview » tutorial » UI » user interface » A Guide to Android RecyclerView and
CardView
A GUIDE TO ANDROID RECYCLERVIEW AND CARDVIEWPUBBLICATO DA FRANCESCO AZZOLA IN ANDROID, CARDVIEW, JAVA, RECYCLERVIEW, TUTORIAL, UI, USER INTERFACE - ON NOVEMBER 11, 2014 - 2 COMMENTS
The new support library in Android L (Lollipop) introduced two new UI
widgets: RecyclerView and CardView. The RecyclerView is a more advanced
and more flexible version of the ListView. This new component is a big step
because the ListView is one of the most used UI widgets. The CardView
widget, on the other hand, is a new component that does not "upgrade" an
existing component. In this tutorial, I'll explain how to use these two widgets and show how we can mix
them. Let's start by diving into the RecyclerView.
RecyclerView: IntroductionRecyclerView: IntroductionAs I mentioned, RecyclerView is more flexible that ListView even if it introduces some complexities. We all
know how to use ListView in our app and we know if we want to increase the ListView performances we can
use a pattern called ViewHolder. This pattern consists of a simple class that holds the references to the UI
components for each row in the ListView. This pattern avoids looking up the UI components all the time the
system shows a row in the list. Even if this pattern introduces some benefits, we can implement the ListView
without using it at all. RecyclerView forces us to use the ViewHolder pattern. To show how we can use the
RecyclerView, we can suppose we want to create a simple app that shows a list of contact cards. The first
thing we should do is create the main layout. RecyclerView is very similar to the ListView and we can use
them in the same way:
As you'll notice from the layout shown above, the RecyclerView is available in the Android support library, so
we have to modify build.gradle to include this dependency:
Now, in the onCreate method we can get the reference to our RecyclerView and configure it:
If you look at the code above, you'll notice some differences between the RecyclerView and ListView.
17
123456789
1011121314
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MyActivity"> <android.support.v7.widget.RecyclerView android:id="@+id/cardList" android:layout_width="match_parent" android:layout_height="match_parent"/> </RelativeLayout>
12345
dependencies {...compile 'com.android.support:recyclerview-v7:21.0.0' }
1 <a name="more"></a>
123456789
10
@Overrideprotected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_my); RecyclerView recList = (RecyclerView) findViewById(R.id.cardList); recList.setHasFixedSize(true); LinearLayoutManager llm = new LinearLayoutManager(this); llm.setOrientation(LinearLayoutManager.VERTICAL); recList.setLayoutManager(llm);}
?
?
?
?
SURVIVING W/ ANDROIDANDROID DEVELOPMENT BLOG TUTORIALS ABOUT ANDROID DEV TOPICS
Search here.... ! " # + %
RecyclerView requires a layout manager. This component positions item views inside the row and
determines when it is time to recycle the views. The library provides a default layout manager called
LinearLayoutManager.
CardViewThe CardView UI component shows information inside cards. We can customise its corners, the
elevation and so on. We want to use this component to show contact information. These cards will be the
rows of RecyclerView and we will see later how to integrate these two components. By now, we can define
our card layout:
As you can see, the CardView is very simple to use. This component is available in another android support
library so we have to add this dependency too:
RecyclerView: AdapterRecyclerView: AdapterThe adapter is a component that stands between the data model we want to show in our app UI and the UI
component that renders this information. In other words, an adapter guides the way the information are
shown in the UI. So if we want to display our contacts, we need an adapter for the RecyclerView. This adapter
must extend a class called RecyclerView.Adapter passing our class that implements the ViewHolder pattern:
We now have to override two methods so that we can implement our logic: onCreateViewHolder is called
whenever a new instance of our ViewHolder class is created, and onBindViewHolder is called when the OS
binds the view with the data -- or, in other words, the data is shown in the UI. In this case, the adapter helps
us combine the RecyclerView and CardView. The layout we defined before for the cards will be the row layout
of our contact list in the RecyclerView. Before doing it, we have to define our data model that stands at the
base of our UI (i.e. what information we want to show). For this purpose, we can define a simple class:
123456789
101112131415161718192021222324252627282930313233343536373839404142434445464748495051
<android.support.v7.widget.CardView xmlns:card_view="http://schemas.android.com/apk/res-auto" xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/card_view" android:layout_width="match_parent" android:layout_height="match_parent" card_view:cardCornerRadius="4dp" android:layout_margin="5dp"> <RelativeLayout android:layout_width="match_parent" android:layout_height="match_parent"> <TextView android:id="@+id/title" android:layout_width="match_parent" android:layout_height="20dp" android:background="@color/bkg_card" android:text="contact det" android:gravity="center_vertical" android:textColor="@android:color/white" android:textSize="14dp"/> <TextView android:id="@+id/txtName" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Name" android:gravity="center_vertical" android:textSize="10dp" android:layout_below="@id/title" android:layout_marginTop="10dp" android:layout_marginLeft="5dp"/> <TextView android:id="@+id/txtSurname" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Surname" android:gravity="center_vertical" android:textSize="10dp" android:layout_below="@id/txtName" android:layout_marginTop="10dp" android:layout_marginLeft="5dp"/> <TextView android:id="@+id/txtEmail" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Email" android:textSize="10dp" android:layout_marginTop="10dp" android:layout_alignParentRight="true" android:layout_marginRight="150dp" android:layout_alignBaseline="@id/txtName"/></RelativeLayout>
1234
dependencies { compile 'com.android.support:cardview-v7:21.0.0' compile 'com.android.support:recyclerview-v7:21.0.0'}
1 public class MyAdapter extends RecyclerView.Adapter<MyHolder> { ..... }
12345
public class ContactInfo { protected String name; protected String surname; protected String email; protected static final String NAME_PREFIX = "Name_";
?
?
?
?
And finally, we are ready to create our adapter. If you remember what we said before about Viewholder
pattern, we have to code our class that implements it:
Look at the code, in the class constructor we get the reference to the views we defined in our card layout.
Now it is time to code our adapter:
In our implementation, we override onBindViewHolder where we bind the data (our contact info) to the
Views. Notice that we don't look up UI components but simply use the references stored in our
ContactViewHolder. In onCreateViewHolder we return our ContactViewHolderinflating the row layout (the
CardView in our case). Run the app and you'll get the results shown below:
678
protected static final String SURNAME_PREFIX = "Surname_"; protected static final String EMAIL_PREFIX = "email_";}
123456789
1011121314
public static class ContactViewHolder extends RecyclerView.ViewHolder { protected TextView vName; protected TextView vSurname; protected TextView vEmail; protected TextView vTitle; public ContactViewHolder(View v) { super(v); vName = (TextView) v.findViewById(R.id.txtName); vSurname = (TextView) v.findViewById(R.id.txtSurname); vEmail = (TextView) v.findViewById(R.id.txtEmail); vTitle = (TextView) v.findViewById(R.id.title); }}
123456789
10111213141516171819202122232425262728293031323334
public class ContactAdapter extends RecyclerView.Adapter<ContactAdapter.ContactViewHolder> { private List<ContactInfo> contactList; public ContactAdapter(List<ContactInfo> contactList) { this.contactList = contactList; } @Override public int getItemCount() { return contactList.size(); } @Override public void onBindViewHolder(ContactViewHolder contactViewHolder, int i) { ContactInfo ci = contactList.get(i); contactViewHolder.vName.setText(ci.name); contactViewHolder.vSurname.setText(ci.surname); contactViewHolder.vEmail.setText(ci.email); contactViewHolder.vTitle.setText(ci.name + " " + ci.surname); } @Override public ContactViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) { View itemView = LayoutInflater.from(viewGroup.getContext()). inflate(R.layout.card_layout, viewGroup, false); return new ContactViewHolder(itemView); } public static class ContactViewHolder extends RecyclerView.ViewHolder { ... }}
?
?
If you like my work and want to help me tokeep this blog free, please support me clicking
Android ListViewcontext menu: Acti...
Android listviewbackground row sty...
Develop androidweather app with Ma...
Android promotedActions: Floating ...
Android ServiceTutorial
Android UML : Designan App – Part ...
Android ListView Pullto Refresh
Android Action Bar(ActionBar) Tab ...
RELATED POSTS :
RELATEDPOSTS :
Newer Post Older Post
Source code available @github
This post was originaly published on Binpress.
ETICHETTE: ANDROID, CARDVIEW, JAVA, RECYCLERVIEW, TUTORIAL, UI, USER INTERFACE
Home
4960 233Google + 45 388DZone 511Reddit 3
on the banner.
Help me to share this blog and give +1 clickingbelow
407
FOLLOW MEFOLLOW ME
ARCHIVIO BLOGARCHIVIO BLOG
► ► 20152015 (3)
▼ ▼ 20142014 (26)
▼ ▼ NovemberNovember (2)
A Guide to Android RecyclerView andA Guide to Android RecyclerView andCardViewCardView
Develop android weather app withDevelop android weather app withMaterial DesignMaterial Design
► ► OctoberOctober (1)
► ► SeptemberSeptember (2)
► ► AugustAugust (1)
► ► JulyJuly (1)
► ► JuneJune (1)
► ► MayMay (4)
► ► AprilApril (4)
► ► MarchMarch (4)
► ► FebruaryFebruary (3)
► ► JanuaryJanuary (3)
► ► 20132013 (32)
► ► 20122012 (19)
SUPPORT THIS BLOGSUPPORT THIS BLOG
POPULAR POSTSPOPULAR POSTS
Android ListView – Tutorial and basic exampleAndroid ListView – Tutorial and basic example
Android ListView : Custom Filter and Filterable interfaceAndroid ListView : Custom Filter and Filterable interface
Android HTTP Client: GET, POST, Download, Upload, MultipartAndroid HTTP Client: GET, POST, Download, Upload, Multipart
RequestRequest
++ &&
Android weather app: JSON, HTTP and OpenweathermapAndroid weather app: JSON, HTTP and Openweathermap
Android Fragment transaction: FragmentManager and BackstackAndroid Fragment transaction: FragmentManager and Backstack
Android SlidingPaneLayout: TutorialAndroid SlidingPaneLayout: Tutorial
FOLLOW SWAFOLLOW SWA
POST PIÙ POPOLARIPOST PIÙ POPOLARI
Topics covered Android ListViewSimpleAdapter ...
In the previous post we showed theway we can...
Topics covered HTTP connectionPost request ...
© 2012-2015 Survivingwithandroid.com
All Rights Reserved. Reproduction without explicitpermission is prohibited.
FOLLOW SWA BY EMAILFOLLOW SWA BY EMAIL
CHECK MY APPCHECK MY APPCATEGORIES
' Android ListView – Tutorial andbasic example
'
' Android ListView : Custom Filter andFilterable interface
'
' Android HTTP Client: GET, POST,Download, Upload, MultipartRequest
'
Android weather app: JSON, HTTP andOpenweathermap
'
Android Blog' Contact me'
About Me'
Email address... Submit
android UI ListView tutorial androidweather http Fragment Adapter android studioapp actionbar activity android volley custom view
eclipse json weather aar adt aidl androd
android app
tutorial android service animation apache app tutorial
asynctask client custom adapter design free gradle
intent intentservice ipc layout market material design
navigation nfc onTouchEvent openweathermap os x
peg board recyclerview remote service sensor service
Topics covered How to developweather app ...
Topics covered Android FragmentFragment...
Topics covered AndroidSlidingPaneLayout ...
Topics covered Android ListViewArray Adapter ...
Topics covered AndroidSwipeRefreshLayout ...
In this post i want to analyze how touse ListView ...
Topics covered Android WeatherApp Yahoo...
'
' Android Fragment transaction:FragmentManager and Backstack
'
' Android SlidingPaneLayout: Tutorial'
' Android ListView : Custom Adapterand Layout
'
' Android SwipeRefreshLayoutTutorial
'
' Android ListView withSectionIndexer and fast scroll
'
' Android Weather app Tutorial: Stepby Step guide (Part 2)
'
slidingpanelayout uml volley weather app xml parser
ExpandableListView Filter OnClickListener SimpleAdapter
account achartengine android bound service
android
broadcastreceiver android camera android chart
android
html parsing android library android location api
android
nfc android torch app android wear apn
autocompletetextview avd back button barometer
bluetooth board bound service broadcast receiver button
camera camera flash cardview chart client lib
consume
service consume webservice custom component denisty
deserialization. diagram drive drop down navigation
emulator endless adapter error example face face detect
face recognition flash light floating action button forecast
fragments free app genymotion google haxm
high pass
filter http post import library inter process coimmunication
java jsoup lib link location locationManager ltiple screen
mac maven central menu money motionevent
multipart
request navigation drawer ndef ndef text network
opensource orbitix parcelable parse parser pitch plugin
process project structure promoted actions publish maven
pull-to-refresh restful resultreceiver rtd save layout sdk
sensorlistener sensormanager serialization
shake to
refresh share smart poster source code sphero sphero API
start service stats swiperefreshlayout tab tag text to speech
toolbar tts use case user interface view holder viewpager
voice webservice well known type xml yahoo weather
provider
© Copyright 2013 Surviving W/ Android - All Rights Reserved - Distributed By Gooyaabi Templates | Powered By Blogger
Template by Kang Ismet Published by GBTemplatesTemplate by Kang Ismet Published by GBTemplates