我有一个RecyclerView
,其中包含从互联网上检索到的项目列表。所以首先,列表将为空。从互联网上检索数据后,它将更新列表并致电notifyDataSetChanged()
。
我可以将数据调整到RecyclerView
就好了。但是,如果点击了每个项目,我会有一个ImageButton
。如果我在onBindViewHolder
内初始化flags数组,每次滚动RecyclerView
时,标志数组将重新初始化为false
。如果我在Adapter
构造函数中初始化它,它将是0索引,因为列表最初将为空。如果数据将在稍后的某个时间内出现,我应该在适配器中将数组初始化放在哪里?
下面是我的代码,但每次滚动isTrue
时,标志数组(RecyclerView
)都会重新初始化。
public class SomethingAdapter extends RecyclerView.Adapter<SomethingAdapter.ViewHolder> {
private ArrayList<String> someList;
private boolean[] isTrue;
public static class ViewHolder extends RecyclerView.ViewHolder {
public TextView someText;
public ImageButton someButton;
public ViewHolder(View v) {
super(v);
someText = (TextView) v.findViewById(R.id.text);
someButton = (ImageButton) v.findViewById(R.id.button);
}
}
public SomethingAdapter(ArrayList<String> someList) {
this.someList = someList;
}
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.some_layout, parent, false);
return new ViewHolder(v);
}
@Override
public void onBindViewHolder(final ViewHolder viewHolder, final int position) {
//TODO: This thing will make isTrue always reinitialize if scrolled
this.isTrue = new boolean[someList.getResults().size()];
viewHolder.someText.setText(someList.get(position));
if (isTrue[position]) {
viewHolder.someButton.setImageResource(R.drawable.button_true);
} else {
viewHolder.someButton.setImageResource(R.drawable.button_false);
}
viewHolder.someButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (isTrue[position]) {
//Connect to the internet and if response is positive {
//isTrue[position] = false;
//viewHolder.someButton.setImageResource(R.drawable.button_false);
//}
} else {
//Connect to the internet and if response is positive {
//isTrue[position] = true;
//viewHolder.someButton.setImageResource(R.drawable.button_true);
//}
}
}
});
}
@Override
public int getItemCount() {
return someList.size();
}
&#13;
答案 0 :(得分:0)
将项目添加到someList
时初始化。
另外,请勿在onBind中添加点击监听器,并在onCreateViewHolder
中创建。你不能在点击回调中使用位置,而应该使用ViewHolder#getAdapterPosition。
有关详细信息,请参阅文档: https://developer.android.com/reference/android/support/v7/widget/RecyclerView.Adapter.html#onBindViewHolder(VH,int)