notigyDataSetChanged不起作用! 在notifyDataSetChanged方法之后,适配器中的列表仍为空。
MainActivity:
//left menu
mRvLeftMenu = (RecyclerView) mSlidingMenu.findViewById(R.id.rv_left_menu);
//set layout manager
mRvLeftMenu.setLayoutManager(new LinearLayoutManager(this));
//init list
mSlidingData = new ArrayList<>();
mLeftMenuAdapter = new LeftMenuAdapter(this, mSlidingData);
//set adapter
mRvLeftMenu.setAdapter(mLeftMenuAdapter);
@Override
public void onLoadFinished(int requestType, BaseResultBean resultBean) {
switch (requestType) {
case MyConstants.REQUEST_RESULT_NEWS_CENTER:
List<NewsResultBean.DataBean> list = ((NewsResultBean) resultBean).getData();
效果很好
// mLeftMenuAdapter = new LeftMenuAdapter(this, list);
// mRvLeftMenu.setAdapter(mLeftMenuAdapter);
如果我只是将数据添加到mSlidingData它没有工作,RecyclerView就不会刷新!为什么呢?
mSlidingData.addAll(list);
mLeftMenuAdapter.notifyDataSetChanged();
并且在notifyDataSetChanged调用之后,适配器中的mList仍为空!与贝娄相同。
mRvLeftMenu.getAdapter().notifyDataSetChanged();
break;
}
}
适配器:
public class LeftMenuAdapter extends RecyclerView.Adapter<LeftMenuAdapter.VH> {
private List<NewsResultBean.DataBean> mList;
private Context mContext;
private OnItemClickListener mOnItemClickListener;
public LeftMenuAdapter(Context context, List<NewsResultBean.DataBean> list) {
mList = list;
mContext = context;
}
@Override
public VH onCreateViewHolder(ViewGroup parent, int viewType) {
View view = View.inflate(mContext, R.layout.item_left_menu, null);
return new VH(view);
}
@Override
public void onBindViewHolder(final VH holder, int position) {
holder.mTvLeftMenu.setText(mList.get(position).getTitle());
final int tempPosition = position;
holder.mView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (mOnItemClickListener != null){
mOnItemClickListener.onItemClicked(v,tempPosition);
}
}
});
}
@Override
public int getItemCount() {
return mList.size();
}
class VH extends RecyclerView.ViewHolder {
@BindView(R.id.tv_left_menu)
TextView mTvLeftMenu;
View mView;
public VH(View itemView) {
super(itemView);
mView = itemView;
ButterKnife.bind(this,mView);
}
}
interface OnItemClickListener{
void onItemClicked(View view,int position);
}
public void setOnItemClickListener(OnItemClickListener onItemClickListener) {
mOnItemClickListener = onItemClickListener;
}
}
答案 0 :(得分:0)
THX为你的帮助伙伴! 我犯了一个愚蠢的错误,我在网络请求后将mSlidingData更改为另一个列表。
//after network request
private void processResult(String response) {
Gson gson = new Gson();
NewsResultBean newsResultBean = gson.fromJson(response, NewsResultBean
.class);
Log.d(TAG, "onResponse: " + newsResultBean.toString());
//pass the result data to MainActivity,changed the mSlidingData to a new list,
//cause RecyclerView notifyDataSetChanged method not work!
// mActivity.setSlidingData(newsResultBean.getData());
像这样的setSlidingData方法:
public void setSlidingData(List<NewsResultBean.DataBean> slidingData) {
mSlidingData = slidingData;
}