Binding List Items

Binding is taking Java code (like model data in a Crime, or click listeners) and hooking it up to a widget. So far, in all the exercises up until this point in the book, you bound each and every time you inflated a view. This meant there was no need to split that work into its own method. However, now that views are being recycled, it pays to have creation in one place and binding in another.

All the code that will do the real work of binding will go inside your CrimeHolder. That work starts with pulling out all the widgets you are interested in. This only needs to happen one time, so write this code in your constructor.

Listing 8.21  Pulling out views in the constructor (CrimeListFragment.java)

private class CrimeHolder extends RecyclerView.ViewHolder {

    private TextView mTitleTextView;
    private TextView mDateTextView;

    public CrimeHolder(LayoutInflater inflater, ViewGroup parent) {
        super(inflater.inflate(R.layout.list_item_crime, parent, false));

        mTitleTextView = (TextView) itemView.findViewById(R.id.crime_title);
        mDateTextView = (TextView) itemView.findViewById(R.id.crime_date);
    }
}

Your CrimeHolder will also need a bind(Crime) method. This will be called each time a new Crime should be displayed in your CrimeHolder. First, add bind(Crime).

Listing 8.22  Writing a bind(Crime) method (CrimeListFragment.java)

private class CrimeHolder extends RecyclerView.ViewHolder {

    private Crime mCrime;
    ...
    public void bind(Crime crime) {
        mCrime = crime;
        mTitleTextView.setText(mCrime.getTitle());
        mDateTextView.setText(mCrime.getDate().toString());
    }
}

When given a Crime, CrimeHolder will now update the title TextView and date TextView to reflect the state of the Crime.

Next, call your newly minted bind(Crime) method each time the RecyclerView requests that a given CrimeHolder be bound to a particular crime.

Listing 8.23  Calling the bind(Crime) method (CrimeListFragment.java)

private class CrimeAdapter extends RecyclerView.Adapter<CrimeHolder> {
    ...
    @Override
    public void onBindViewHolder(CrimeHolder holder, int position) {
        Crime crime = mCrimes.get(position);
        holder.bind(crime);
    }
    ...
}

Run CriminalIntent one more time, and every visible CrimeHolder should now display a distinct Crime (Figure 8.11).

Figure 8.11  All right, all right, all right

All right, all right, all right

When you fling the view up, the scrolling animation should feel as smooth as warm butter. This effect is a direct result of keeping onBindViewHolder(…) small and efficient, doing only the minimum amount of work necessary.

Take heed: Always be efficient in your onBindViewHolder(…). Otherwise, your scroll animation could feel as chunky as cold Parmesan cheese.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.14.70.203