I have a question about the event CrimeHolder.onClick

#1

Hi,

I studied chapter 10 of the book. But I can not understand: when you click on a list item, the CrimeHolder.onClick method is called. The method code looks like this:

Intent intent = CrimeActivity.newIntent(getActivity(), mCrime.getId());
startActivityForResult(intent, REQUEST_CRIME);

The author of the book uses mCrime.getId () as a parameter. But I do not understand how the link to the clicked list item is written in the mCrime before calling the CrimeHolder.onClick method.

What is the sequence of method invocation at the moment of clicking on a list item.

Using the debugger, I could not catch it. I tried to set a data breakpoint on the variable mCrime, But before calling the CrimeHolder.onClick method, the variable mCrime does not change its value

How it works?

#2
private class CrimeHolder extends RecyclerView.ViewHolder
        implements View.OnClickListener {

    private Crime mCrime;

    private TextView mTitleTextView;
    private TextView mDateTextView;
    private ImageView mSolvedImageView;

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

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

    public void bind(Crime crime) {
        mCrime = crime;
        mTitleTextView.setText(mCrime.getTitle());
        mDateTextView.setText(mCrime.getDate().toString());
        mSolvedImageView.setVisibility(crime.isSolved() ? View.VISIBLE : View.GONE);
    }

    @Override
    public void onClick(View view) {
        Intent intent = CrimeActivity.newIntent(getActivity(), mCrime.getId());
        startActivity(intent);
    }
}

Just before a item in the list becomes visible to the user, we call the bind(Crime) method to tell it to update what it shows to this new crime. In that method, we are setting the mCrime instance variable. So, when you click on that item, the instance variable is already set and you can use the correct ID.

#3

I understand how work bind.
But if 10 list items are visible on the screen, then the bind is sequentially called for these 10 elements. The last call will be for the tenth element. Correspondingly, in the variable mCrime there will be a reference to the tenth element. But the user clicks on the fourth visible element, how in this case the correct link is written to the mCrime variable?

#4

If there are 10 visible items, then there are (at least) 10 different CrimeHolders, each with their own mCrime and view references. This crime reference remains unchanged until either the CrimeHolder is recycled or the CrimeAdapter is notified of an item change.

#5

Thanks, now I understand how it works