wmo*_*ora 26 android custom-adapter android-support-library android-recyclerview
我正在使用Android的新RecyclerView,但每当我调用其中一个"notify"方法时,我都无法刷新我的自定义适配器.
我试过调用notifyDataSetChanged,notifyItemRangeInserted和notifyItemInserted,但它们似乎都没有工作.
这是我的自定义适配器的代码.我基本上试图刷新一个字符串列表:
package com.mycompany.myapp.adapters;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.mycompany.myapp.R;
import java.util.List;
public class FeedAdapter extends RecyclerView.Adapter<FeedAdapter.ViewHolder> {
private List<String> mDataset;
public FeedAdapter(List<String> dataset) {
super();
mDataset = dataset;
}
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int i) {
LinearLayout v = (LinearLayout) LayoutInflater.from(parent.getContext())
.inflate(R.layout.list_item_feed, parent, false);
v.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.WRAP_CONTENT));
return new ViewHolder(v);
}
@Override
public void onBindViewHolder(ViewHolder holder, int position) {
holder.setText(mDataset.get(position));
}
@Override
public int getItemCount() {
return mDataset.size();
}
public void setDataset(List<Status> dataset) {
mDataset = dataset;
// This isn't working
notifyItemRangeInserted(0, mDataset.size());
}
public static class ViewHolder extends RecyclerView.ViewHolder {
private TextView mFeedText;
public ViewHolder(View v) {
super(v);
mFeedText = (TextView) v.findViewById(R.id.feed_text);
}
private void setText(String text) {
mFeedText.setText(text);
}
}
}
Run Code Online (Sandbox Code Playgroud)
还有谁有相同的问题吗?
谢谢!
kos*_*cki 11
我试图使用notifyDataSetChanged()方法更新RecycleView以响应com.google.common.eventbus.Subscribe.
就像@wmora提到的那样,问题是在主UI线程中没有调用notify方法.
我用AndroidAnnotations的@UiThread解决了这个问题
@UiThread
protected void dataSetChanged() {
notifyDataSetChanged();
}
Run Code Online (Sandbox Code Playgroud)
这相当于:
final Adapter adapter = this;
new Handler(Looper.getMainLooper()).post(new Runnable() {
@Override
public void run() {
adapter.notifyDataSetChanged();
}
});
Run Code Online (Sandbox Code Playgroud)
注意:只需将新的Handler分隔为类私有字段
| 归档时间: |
|
| 查看次数: |
40823 次 |
| 最近记录: |