public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
RecyclerView list = (RecyclerView) findViewById(R.id.list);
list.setLayoutManager(new LinearLayoutManager(this));
final RecyclerView.Adapter adapter = getAdapter();
list.setAdapter(adapter);
adapter.notifyItemChanged(1, new Object());//this doesn't work
list.post(new Runnable() {
@Override
public void run() {
adapter.notifyItemChanged(1, new Object());//this works
}
});
}
@NonNull
private RecyclerView.Adapter getAdapter() {
return new RecyclerView.Adapter() {
@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
return new ItemViewHolder( LayoutInflater.from(parent.getContext())
.inflate(R.layout.list_view_item, parent, false));
}
@Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
ItemViewHolder item = (ItemViewHolder) holder;
item.tv.setText("test");
}
@Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position, List payloads) {
if(payloads.isEmpty())
onBindViewHolder(holder, position);
else{
ItemViewHolder item = (ItemViewHolder) holder;
item.tv.setText("changed!!!!!! ");
}
}
@Override
public int getItemCount() {
return 40;
}
class ItemViewHolder extends RecyclerView.ViewHolder{
TextView tv;
ItemViewHolder(View itemView) {
super(itemView);
tv = (TextView) itemView.findViewById(R.id.tv);
}
}
};
}}
very simple example here just to test notifyItemChanged
, it works only when post to the Message queue, but not by invoking directly after setAdapter
.
setAdapter
triggers a call to requestlayout()
, does that mean notifyItemChanged
can't happen if it is in middle of laying out items?