我有一個ArrayList
<字符串>帶有6個項目{「1」,「2」,「3」,「4」,「5」, 「6」}。從自定義的RecycleView適配器中刪除項目,並通過向右滑動項目順序
我代表這些項目與CardView
。我想通過向左滑動來移除項目。
它看起來像這樣:http://imgur.com/cuWoiB3
當我從2號向右滑動,它看起來像這樣:http://imgur.com/5E9fwP0
如果我刪除5號,它消除了2號。如果我刪除3號,它刪除數字1.它似乎是完全隨機的。
我在這裏錯過了什麼嗎?我該如何解決?
相關代碼:
我的適配器:
public class ChoresAdapter extends RecyclerView.Adapter<ChoresAdapter.ChoreViewHolder>{
private ArrayList<String> chores;
public ChoresAdapter(ArrayList<String> chores){
this.chores = chores;
}
@Override
public ChoreViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.single_cardview, parent, false);
v.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
}
});
ChoreViewHolder pvh = new ChoreViewHolder(v);
return pvh;
}
@Override
public void onBindViewHolder(ChoreViewHolder holder, int position) {
holder.choreName.setText(this.chores.get(position));
}
@Override
public int getItemCount() {
return this.chores.size();
}
public void removeAt(int position) {
this.chores.remove(position);
notifyItemRemoved(position);
notifyDataSetChanged();
}
public static class ChoreViewHolder extends RecyclerView.ViewHolder {
CardView cv;
public static TextView choreName;
public static TextView personAge;
public static ImageView personPhoto;
ChoreViewHolder(View itemView) {
super(itemView);
cv = (CardView)itemView.findViewById(R.id.cv);
choreName = (TextView)itemView.findViewById(R.id.chore_name);
}
}
}
相關的代碼在我的片段:
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_chores, container, false);
RecyclerView rv = (RecyclerView)view.findViewById(R.id.rv);
rv.setHasFixedSize(true);
LinearLayoutManager llm = new LinearLayoutManager(getActivity());
rv.setLayoutManager(llm);
chores = new ArrayList<>();
chores.add("1");
chores.add("2");
chores.add("3");
chores.add("4");
chores.add("5");
chores.add("6");
adapter = new ChoresAdapter(chores);
SwipeableRecyclerViewTouchListener swipeTouchListener =
new SwipeableRecyclerViewTouchListener(rv,
new SwipeableRecyclerViewTouchListener.SwipeListener() {
@Override
public boolean canSwipe(int position) {
return true;
}
@Override
public void onDismissedBySwipeLeft(RecyclerView recyclerView, int[] reverseSortedPositions) {
for (int position : reverseSortedPositions) {
adapter.removeAt(position);
}
}
@Override
public void onDismissedBySwipeRight(RecyclerView recyclerView, int[] reverseSortedPositions) {
for (int position : reverseSortedPositions) {
adapter.removeAt(position);
}
}
});
rv.addOnItemTouchListener(swipeTouchListener);
rv.setAdapter(adapter);
return view;
}