User Interaction
Now your list has function and style. What's it missing now? Try tapping or long pressing it. There's not much to thrill and delight the user.
What could you add here to make the user experience that much more satisfying? Well, when a user taps on a row, don't you think it'd be nice to show the full recipe, complete with instructions?
You’ll make use of AdapterView.onItemClickListener and a brand spanking new activity to do this with elegance.
Make a New Activity
This activity will display when the user selects an item in the list.
Right-click on java/com.raywenderlich.alltherecipes then select New > Activity > EmptyActivity to bring up a dialog. Fill in the Activity Name with RecipeDetailActivity. Leave the automatically populated fields as-is. Check that your settings match these:
Click Finish.
Open res/layout/activity_recipe_detail.xml and add a
WebView
by inserting the following snippet inside the RelativeLayout
tag:<WebView
android:id="@+id/detail_web_view"
android:layout_width="match_parent"
android:layout_height="match_parent" />
WebView
will be used to load and display a webpage containing the selected recipe's instructions.
Open up RecipeDetailActivity.java, and add a
WebView
reference as an instance variable by adding the following line within the class definition:private WebView mWebView;
Head back to MainActivity.java and add the following to the bottom of the
onCreate
method:final Context context = this;
mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// 1
Recipe selectedRecipe = recipeList.get(position);
// 2
Intent detailIntent = new Intent(context, RecipeDetailActivity.class);
// 3
detailIntent.putExtra("title", selectedRecipe.title);
detailIntent.putExtra("url", selectedRecipe.instructionUrl);
// 4
startActivity(detailIntent);
}
});
Note: Before you dive into the explanation, make sure you understand the four arguments that are provided by
onItemClick
; they work as follows:- parent: The view where the selection happens -- in your case, it's the ListView
- view: The selected view (row) within the ListView
- position: The position of the row in the adapter
- id: The row id of the selected item
The first thing you do in the last snippet is set the
OnItemClickListener
object for the ListView. The OnItemClickListener
class has a method named onItemClick
that you override -- more on that in a moment.
At
@Override
, you override the existing onItemClick
method and implement the following steps:- Get the recipe object for the row that was clicked
- Create an intent to navigate to your
RecipeDetailActivity
to display more information - Let the
RecipeDetailActivity
know the title and URL of the recipe to display by passing that data via the Intent. - Launch the
RecipeDetailActivity
by passing the intent object you just created to thestartActivity()
method.
Note: To learn more about intents, check out the awesome Android: Intents Tutorial.
Once again, open RecipeDetailActivity.java and add the following snippet at the bottom of the
onCreate
method:// 1
String title = this.getIntent().getExtras().getString("title");
String url = this.getIntent().getExtras().getString("url");
// 2
setTitle(title);
// 3
mWebView = (WebView) findViewById(R.id.detail_web_view);
// 4
mWebView.loadUrl(url);
You can see a few things happening here:
- You retrieve the recipe data from the
Intent
passed byMainActivity
by using thegetExtras()
method. - You set the title on the action bar of this activity to the recipe title.
- You initialize
mWebView
to the web view defined in the XML layout. - You load the recipe web page by calling
loadUrl()
with the corresponding recipe's URL on the web view object.
Build and run. When you click on the first item in the list, you should see something like this:
Optimizing Performance
Whenever you scroll the ListView, its adapter's
getView()
method is called in order to create a row and display it on screen.
Now, if you look in your
getView()
method, you'll notice that each time this method is called, it performs a lookup for each of the row view's elements by using a call to the findViewById()
method.
These repeated calls can seriously harm the ListView's performance, especially if your app is running on limited resources and/or you have a very large list. You can avoid this problem by using the View Holder Pattern.
Implement a ViewHolder Pattern
To implement the ViewHolder pattern, open RecipeAdapter.java and add the following after the
getView()
method definition:private static class ViewHolder {
public TextView titleTextView;
public TextView subtitleTextView;
public TextView detailTextView;
public ImageView thumbnailImageView;
}
As you can see, you create a class to hold your exact set of component views for each row view. The
ViewHolder
object stores each of the row's subviews, and in turn is stored inside the tag field of the layout.
This means you can immediately access the row's subviews without the need to look them up repeatedly.
Now, in
getView()
, replace everything above (but NOT including) this line:Recipe recipe = (Recipe) getItem(position);
With:
ViewHolder holder;
// 1
if(convertView == null) {
// 2
convertView = mInflater.inflate(R.layout.list_item_recipe, parent, false);
// 3
holder = new ViewHolder();
holder.thumbnailImageView = (ImageView) convertView.findViewById(R.id.recipe_list_thumbnail);
holder.titleTextView = (TextView) convertView.findViewById(R.id.recipe_list_title);
holder.subtitleTextView = (TextView) convertView.findViewById(R.id.recipe_list_subtitle);
holder.detailTextView = (TextView) convertView.findViewById(R.id.recipe_list_detail);
// 4
convertView.setTag(holder);
}
else{
// 5
holder = (ViewHolder) convertView.getTag();
}
// 6
TextView titleTextView = holder.titleTextView;
TextView subtitleTextView = holder.subtitleTextView;
TextView detailTextView = holder.detailTextView;
ImageView thumbnailImageView = holder.thumbnailImageView;
Here's the play-by-play of what's happening above.
- Check if the view already exists. If it does, there's no need to inflate from the layout and call
findViewById()
again. - If the view doesn't exist, you inflate the custom row layout from your XML.
- Create a new
ViewHolder
with subviews initialized by usingfindViewById()
. - Hang onto this holder for future recycling by using
setTag()
to set the tag property of the view that the holder belongs to. - Skip all the expensive inflation steps and just get the holder you already made.
- Get relevant subviews of the row view.
Finally, update the return statement of
getView()
with the line below.return convertView;
Build and run. If your app was running a bit slow on the last build, you should see it running smoother now. :]
Nenhum comentário:
Postar um comentário