重写onResume()方法实现activity的刷新
时间: 2024-02-16 11:03:42 浏览: 152
好的,针对你的问题,我给出以下实现:
```java
public class RefreshActivity extends AppCompatActivity {
private RecyclerView mRecyclerView;
private List<String> mDataList;
private MyAdapter mAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_refresh);
// 初始化 RecyclerView
mRecyclerView = findViewById(R.id.recycler_view);
mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
mDataList = new ArrayList<>();
mAdapter = new MyAdapter(mDataList);
mRecyclerView.setAdapter(mAdapter);
}
@Override
protected void onResume() {
super.onResume();
// 刷新数据
mDataList.clear();
mDataList.addAll(getDataList());
mAdapter.notifyDataSetChanged();
}
private List<String> getDataList() {
// 模拟获取数据
List<String> dataList = new ArrayList<>();
for (int i = 0; i < 20; i++) {
dataList.add("数据 " + i);
}
return dataList;
}
private class MyAdapter extends RecyclerView.Adapter<MyViewHolder> {
private List<String> dataList;
public MyAdapter(List<String> dataList) {
this.dataList = dataList;
}
@NonNull
@Override
public MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_layout, parent, false);
return new MyViewHolder(itemView);
}
@Override
public void onBindViewHolder(@NonNull MyViewHolder holder, int position) {
holder.textView.setText(dataList.get(position));
}
@Override
public int getItemCount() {
return dataList.size();
}
}
private class MyViewHolder extends RecyclerView.ViewHolder {
private TextView textView;
public MyViewHolder(@NonNull View itemView) {
super(itemView);
textView = itemView.findViewById(R.id.text_view);
}
}
}
```
这是一个简单的 RecyclerView 刷新示例,我们在 `onResume()` 方法中进行了数据的刷新操作。需要注意的是,我们在 `MyAdapter` 中实现了 `onCreateViewHolder()`、`onBindViewHolder()` 和 `getItemCount()` 方法来设置 RecyclerView 的布局和数据。在 `MyViewHolder` 中我们定义了 `TextView`,用于显示数据。当我们进行数据刷新时,先调用 `getDataList()` 方法获取最新数据,然后通过 `mAdapter.notifyDataSetChanged()` 刷新数据。
阅读全文