Sunlight 3.01 to 3.03 – onItemClickListener on RecyclerView items

Replacing the ListView by RecyclerView required additional code. Setting a simple onItemClickListener on the items does even more. Don’t let the word “complicated” enter your mind. Replace it by “versatile”. 

[*Caution: Outdated content. My sunlight project has been discontinued. It refers to earlier versions of the v7 appcompat Library (21.0.3) and Android Studio (1.1).  I’ll keep the posts online for reference but with the current version of appcompat Library things may be different / easier today, so please refer to more up-to-date sources.]

This article is part of the Sunlight project and refers to Lesson 3  (ItemClickListener and toast) of Googles Udacity Course “Developing Android Apps”.

Raise a toast

Unlike the ListView there is no simple setOnItemClickListener() for a RecyclerView. In the RecyclerView the Adapter is responsible for this job. So we have to make it implement an OnClickListener Interface.

Another difference: We won’t get the value from the mForecastAdapter. The onClick method gets the current view as parameter. So we take the text directly from the TextView element.

Tip: If you need the index of the clicked view, simply use

Switch to detail view

This is just a small variation to the toast. As in the original course we send the text as an Extra:

When the Detail Activity is launched, something ist missing:

Oh, yes. The App Bar. Remember? We set the basic Style for the app to Theme.AppCompat.Light.NoActionBar in one of the first steps.
So as for the MainActivity we have to include our new Toolbar here. Two steps required:

1) Add the toolbar to the activity_detail.xml layout file (and change the layout from FrameLayout to LinearLayout to prevent overlapping)

2) Make the Toolbar behave as AppBar and make it show the “up”-Navigation icon in the DetailActivity class:

If this looks unfamiliar to you, you may want to read this post about replacing the ActionBar by Toolbar.

Now the DetailView looks more complete:

Display the text in DetailFragment

This works pretty much like described in the video. But wait! There is a chance to add a litte extra feature for Android L: Activity Transitions. We will explore this in the next post.

 

Leave a Reply

Your email address will not be published. Required fields are marked *