When setting OnClickListeners
to items in the RecyclerView
it's recommended to do that in the inner class like this:
public ViewHolder(View itemView) {
super(itemVIew);
nameTextView = (TextView) itemView.findViewById(R.id.item_name);
itemView.setOnClickListener(this);
}
When I see code for setting text it's usually in the onBindViewHolder
method:
@Override
public void onBindViewHolder(SetPlayerNameViewHolder holder, int position) {
holder.nameTextView.setText(String.valueOf("Random Text"));
}
If the text never changes, shouldn't it be in the inner class?
public ViewHolder(View itemView) {
super(itemVIew);
nameTextView = (TextView) itemView.findViewById(R.id.item_name);
nameTextView.setText(String.valueOf("Random Text"));
itemView.setOnClickListener(this);
}
Edit: And what if you retrieve a value that is different for all TextViews
, but should not be updated when the RecyclerView
reloads it
public ViewHolder(View itemView) {
super(itemVIew);
nameTextView = (TextView) itemView.findViewById(R.id.item_name);
// Not the actual methods, but to make it more readable
int i = itemView.getPosition()
String randomText = getTextFromDatabaseWhereRowIs(i)
nameTextView.setText(String.valueOf(randomText));
itemView.setOnClickListener(this);
}
Yes you are right...
1. onBindViewHolder(..., int position)
get called for individual
items of RecyclerView
. If your text
is different for each item
then you should use it from onBindViewHolder()
using position
to get the correct text
.
@Override
public void onBindViewHolder(SetPlayerNameViewHolder holder, int position) {
String item = YourList.get(position); // For example YourList is an ArrayList of String
holder.nameTextView.setText(item);
}
2. If text
is fixed for each item
then you can set it from ViewHolder
as you said or you can make it fix from TextView XML
using android:text="YOUR_TEXT"
.
public ViewHolder(View itemView) {
super(itemVIew);
nameTextView = (TextView) itemView.findViewById(R.id.item_name);
nameTextView.setText("Random Text");
}
Hope this will help~