You can use something like this in your activity/fragment
private List<Simple> elements;
private String names[] = {
"Monk's Oartormow",
"Eldoth Nut",
"Eblurst",
"Poison Okule",
"Black Berry",
"Snake Eye",
"Witch's Root",
"White Burm",
"Yellow Pig Claw",
"Uchea Mint"
};
private String contents[] = {
"What if the adaptable injury ate the click?",
"The united chip stuffs into the babyish sad.",
"Did the interesting progress really argue the visual?",
"What if the chief sign ate the schedule?",
"Is the brush respect better than the raise?",
"It was then the inexperienced topic met the open period."
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_flower);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
elements = new ArrayList<>();
adapter = new SimpleAdapter();
RecyclerView recyclerView = findViewById(R.id.recycler_view);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
recyclerView.setAdapter(adapter);
FloatingActionButton fab = findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Simple s = generateRandomElement();
elements.add(0,s);
adapter.updateElements(elements);
}
});
}
private Simple generateRandomElement() {
int posNames = (int) (Math.random() * names.length);
int posContent = (int) (Math.random() * contents.length);
String name = names[posNames];
String content = contents[posContent];
return new Simple(name, content);
}
and for updating the elements in the adapter:
private List<Simple> elements;
public SimpleAdapter() {
this.elements = new ArrayList<>();
}
@Override
public SimpleViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.row_simple_element, parent, false);
return new SimpleViewHolder(view);
}
@Override
public void onBindViewHolder(SimpleViewHolder holder, int position) {
Simple element = elements.get(position);
holder.title.setText(element.getTitle());
holder.content.setText(element.getContent());
}
@Override
public int getItemCount() {
return elements.size();
}
public void updateElements(List<Simple> elements) {
this.elements.clear();
this.elements.addAll(elements);
notifyDataSetChanged();
}
you can improve how the elements are updated implementing a DiffCallback for your Flower class (link)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…