Я пытаюсь отобразить список предметов, используя держатель для повторного просмотра.Элементы могут отображаться с использованием двух разных макетов.
Но когда я пытаюсь преобразовать свой держатель из RecyclerView.ViewHolder в тип моего видоискателя, у меня возникает ошибка приведения
(я пытаюсьиспользовать возврат к просмотру вместо списка просмотра, потому что, как я и пытался, мой приемник щелчков на моем элементе списка имел какой-то кеш. Если я отображал первые 10 элементов моего списка, у каждого элемента была позиция элемента регистрации onclicklistener., если я нажму на элемент 11, это будет позиция регистрации 1. Я видел, что я мог бы использовать onDetachedFromWindow, чтобы установить нулевой прослушиватель для моего элемента. Это то, что я пытаюсь сделать с помощью recyclerview)
MyАдаптер повторного просмотра:
public class WaypointArrayAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private static final int CELL_TYPE_CURRENT_POS = 0;
private static final int CELL_TYPE_WAYPOINT = 1;
private List<Cell> cellArrayList;
private List<Waypoint> waypointList;
private LayoutInflater layoutInflater;
private OnItemClickListener mListener;
Context context;
public WaypointArrayAdapter(Context context, List<Cell> cellList, List<Waypoint> waypointList) {
layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
this.context = context;
this.cellArrayList = cellList;
this.waypointList = waypointList;
setListener();
}
public void addItem(Cell cell) {
cellArrayList.add(cell);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public int getItemCount() {
return cellArrayList.size();
}
public class ViewHolderOne extends RecyclerView.ViewHolder implements OnItemClickListener {
public TextView currentPos;
public ViewHolderOne(View v, final OnItemClickListener listener, final int position) {
super(v);
currentPos = (TextView) v.findViewById(R.id.currentposition);
v.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v) {
if(listener != null) {
if(position != RecyclerView.NO_POSITION) {
listener.onItemClick(v,position);
}
}
}
});
}
@Override
public void onItemClick(View v, int position) {
// Void
}
}
public class ViewHolderTwo extends RecyclerView.ViewHolder implements OnItemClickListener {
public TextView distance;
public TextView comment;
public ViewHolderTwo(View v, final OnItemClickListener listener, final int position) {
super(v);
distance = (TextView) v.findViewById((R.id.mileage));
comment = (TextView) v.findViewById(R.id.comment);
v.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v) {
if(listener != null) {
if(position != RecyclerView.NO_POSITION) {
listener.onItemClick(v,position);
}
}
}
});
}
@Override
public void onItemClick(View v, int position) {
// Void
}
}
@NonNull
@Override
public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int position) {
Log.d("GHT","OnCreateViewHolder");
int type = getItemViewType(position);
switch(type) {
case CELL_TYPE_CURRENT_POS:
View view1 = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.currentposition_layout, viewGroup, false);
return new ViewHolderOne(view1,mListener,position);
case CELL_TYPE_WAYPOINT:
View view2 = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.waypoint_layout, viewGroup, false);
return new ViewHolderTwo(view2,mListener,position);
}
return null;
}
@Override
public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {
Log.d("GHT","OnBindViewHolder");
int type = getItemViewType(position);
switch(type) {
case CELL_TYPE_CURRENT_POS:
initCurrentPosLayout((ViewHolderOne)holder,position);
break;
case CELL_TYPE_WAYPOINT:
initWaypointLayout((ViewHolderTwo)holder, position);
break;
}
}
@Override
public int getItemViewType(int position) {
if (cellArrayList.get(position).getClass().getSimpleName().equals("CurrentPosition")) {
return CELL_TYPE_CURRENT_POS;
}
return CELL_TYPE_WAYPOINT;
}
public void setListener() {
mListener = new OnItemClickListener() {
@Override
public void onItemClick(View v, int position) {
Log.d("GHT", "Item clicked ! position = "+position);
MainActivity.selectedId = position;
Intent intent = new Intent(context, WaypointPopup.class);
startActivity(context, intent,null);
}
};
}
public Cell getItem(int position) {return cellArrayList.get(position);}
public void initCurrentPosLayout(ViewHolderOne holder, int position) {
Log.d("GHT","InitCurrentPosLayout");
String currentPos = "";
if(position>0) {
if (PointsUtils.isSnappedToTrail(getItem(position - 1), getItem(position))) {
// On trail
currentPos = "You are on trail km "+PointsUtils.getDistanceFormatted(waypointList.get(PointsUtils.getClosestPoint(getItem(position).getX(),getItem(position).getY(),waypointList)).getDistanceSinceBeg());
} else {
Waypoint closestPoint = waypointList.get(PointsUtils.getClosestPoint(getItem(position).getX(),getItem(position).getY(),waypointList));
double distBetweenThem = PointsUtils.getDistance(getItem(position).getX(),getItem(position).getY(),closestPoint.getX(),closestPoint.getY());
if (distBetweenThem < CLOSE_ENOUGHT_FROM_TRAIL) {
// close enough
currentPos = "You are close to trail km "+PointsUtils.getDistanceFormatted(closestPoint.getDistanceSinceBeg());
} else {
// You are at XXX km of XXX trail point
currentPos = "You are "+PointsUtils.getDistanceFormatted(distBetweenThem)+"km away from trail km "+PointsUtils.getDistanceFormatted(closestPoint.getDistanceSinceBeg());
}
}
} else {
if (PointsUtils.isSnappedToTrail(getItem(position + 1), getItem(position))) {
// On trail
currentPos = "You are on trail km "+PointsUtils.getDistanceFormatted(waypointList.get(PointsUtils.getClosestPoint(getItem(position).getX(),getItem(position).getY(),waypointList)).getDistanceSinceBeg());
} else {
Waypoint closestPoint = waypointList.get(PointsUtils.getClosestPoint(getItem(position).getX(),getItem(position).getY(),waypointList)+1);
double distBetweenThem = PointsUtils.getDistance(getItem(position).getX(),getItem(position).getY(),closestPoint.getX(),closestPoint.getY());
if (distBetweenThem < CLOSE_ENOUGHT_FROM_TRAIL) {
// close enough
currentPos = "You are close to trail km "+PointsUtils.getDistanceFormatted(closestPoint.getDistanceSinceBeg());
} else {
// You are at XXX km of XXX trail point
currentPos = "You are "+PointsUtils.getDistanceFormatted(distBetweenThem)+"km away from trail km "+PointsUtils.getDistanceFormatted(closestPoint.getDistanceSinceBeg());
//currentPos = closestPoint.getName()+" et "+getItem(position).getName();
}
}
}
if (!currentPos.isEmpty())
holder.currentPos.setText(currentPos);
}
public void initWaypointLayout(ViewHolderTwo holder, int position) {
Log.d("GHT","InitWaypointLayout");
int closest = getItem(position).getId();
if(closest>=closestId+1) {
closest++;
}
int listSize = cellArrayList.size();
double distance = PointsUtils.getTrailDistanceBetweenTwoPoints(listSize-closest-1, listSize-closestId-2, cellArrayList);
String distanceFormatted = getDistanceFormatted(distance);
if (!distanceFormatted.isEmpty()) {
holder.distance.setText(getItem(position).getPrefix()+" "+distanceFormatted+"km entre "+cellArrayList.get(listSize-closest-1).getName()+" et "+cellArrayList.get(listSize-closestId-2).getName());
String comment = "GHT km " + getDistanceFormatted(getItem(position).getDistanceSinceBeg()) + " " + getItem(position).getName();
if (!comment.isEmpty())
holder.comment.setText(comment);
}
}
}
Мой фрагмент:
public class ByTrailList extends Fragment {
// ...
@Override
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_by_trail_list, container, false);
waypointListView = (RecyclerView) view.findViewById(android.R.id.list);
waypointListView = (RecyclerView) view.findViewById(android.R.id.list);
displayResult(location);
}
// ...
private void displayResult(Location aLocation) {
// ...
waypointArrayAdapter = new WaypointArrayAdapter(getContext(), cells, waypointList);
waypointListView.setLayoutManager(new LinearLayoutManager(getContext()));
waypointListView.setItemAnimator(new DefaultItemAnimator());
waypointListView.setAdapter(waypointArrayAdapter);
Код ошибки:
2019-06-11 00:41:50.871 21616-21616/com.example.myapplicationtest E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.myapplicationtest, PID: 21616
java.lang.ClassCastException: com.example.myapplicationtest.WaypointArrayAdapter$ViewHolderOne cannot be cast to com.example.myapplicationtest.WaypointArrayAdapter$ViewHolderTwo
at com.example.myapplicationtest.WaypointArrayAdapter.onBindViewHolder(WaypointArrayAdapter.java:134)
at android.support.v7.widget.RecyclerView$Adapter.onBindViewHolder(RecyclerView.java:6781)
at android.support.v7.widget.RecyclerView$Adapter.bindViewHolder(RecyclerView.java:6823)
at android.support.v7.widget.RecyclerView$Recycler.tryBindViewHolderByDeadline(RecyclerView.java:5752)
at android.support.v7.widget.RecyclerView$Recycler.tryGetViewHolderForPositionByDeadline(RecyclerView.java:6019)
at android.support.v7.widget.RecyclerView$Recycler.getViewForPosition(RecyclerView.java:5858)
at android.support.v7.widget.RecyclerView$Recycler.getViewForPosition(RecyclerView.java:5854)
at android.support.v7.widget.LinearLayoutManager$LayoutState.next(LinearLayoutManager.java:2230)
at android.support.v7.widget.LinearLayoutManager.layoutChunk(LinearLayoutManager.java:1557)
at android.support.v7.widget.LinearLayoutManager.fill(LinearLayoutManager.java:1517)
at android.support.v7.widget.LinearLayoutManager.onLayoutChildren(LinearLayoutManager.java:612)
at android.support.v7.widget.RecyclerView.dispatchLayoutStep2(RecyclerView.java:3924)
at android.support.v7.widget.RecyclerView.dispatchLayout(RecyclerView.java:3641)
at android.support.v7.widget.RecyclerView.onLayout(RecyclerView.java:4194)
at android.view.View.layout(View.java:20831)
at android.view.ViewGroup.layout(ViewGroup.java:6203)
at android.support.constraint.ConstraintLayout.onLayout(ConstraintLayout.java:1915)
at android.view.View.layout(View.java:20831)
at android.view.ViewGroup.layout(ViewGroup.java:6203)
at android.support.v4.view.ViewPager.onLayout(ViewPager.java:1775)
at android.view.View.layout(View.java:20831)
at android.view.ViewGroup.layout(ViewGroup.java:6203)
at android.support.design.widget.HeaderScrollingViewBehavior.layoutChild(HeaderScrollingViewBehavior.java:142)
at android.support.design.widget.ViewOffsetBehavior.onLayoutChild(ViewOffsetBehavior.java:41)
at android.support.design.widget.AppBarLayout$ScrollingViewBehavior.onLayoutChild(AppBarLayout.java:1556)
at android.support.design.widget.CoordinatorLayout.onLayout(CoordinatorLayout.java:888)
at android.view.View.layout(View.java:20831)
at android.view.ViewGroup.layout(ViewGroup.java:6203)
at android.widget.FrameLayout.layoutChildren(FrameLayout.java:323)
at android.widget.FrameLayout.onLayout(FrameLayout.java:261)
at android.view.View.layout(View.java:20831)
at android.view.ViewGroup.layout(ViewGroup.java:6203)
at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1812)
at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1656)
at android.widget.LinearLayout.onLayout(LinearLayout.java:1565)
at android.view.View.layout(View.java:20831)
at android.view.ViewGroup.layout(ViewGroup.java:6203)
at android.widget.FrameLayout.layoutChildren(FrameLayout.java:323)
at android.widget.FrameLayout.onLayout(FrameLayout.java:261)
at android.view.View.layout(View.java:20831)
at android.view.ViewGroup.layout(ViewGroup.java:6203)
at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1812)
at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1656)
at android.widget.LinearLayout.onLayout(LinearLayout.java:1565)
at android.view.View.layout(View.java:20831)
at android.view.ViewGroup.layout(ViewGroup.java:6203)
at android.widget.FrameLayout.layoutChildren(FrameLayout.java:323)
at android.widget.FrameLayout.onLayout(FrameLayout.java:261)
at com.android.internal.policy.DecorView.onLayout(DecorView.java:754)
at android.view.View.layout(View.java:20831)
at android.view.ViewGroup.layout(ViewGroup.java:6203)
at android.view.ViewRootImpl.performLayout(ViewRootImpl.java:2991)
2019-06-11 00:41:50.871 21616-21616/com.example.myapplicationtest E/AndroidRuntime: at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:2504)
at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1635)
at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:7795)
at android.view.Choreographer$CallbackRecord.run(Choreographer.java:1172)
at android.view.Choreographer.doCallbacks(Choreographer.java:984)
at android.view.Choreographer.doFrame(Choreographer.java:809)
at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:1158)
at android.os.Handler.handleCallback(Handler.java:873)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:6863)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:537)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)