我正在尝试将Google地图片段添加到
Android中的RecyclerView中.
我正在阅读它,我发现我需要动态创建片段而不是通过XML来创建片段以避免重复的ID错误.
这是我的适配器代码:
public class MapViewHolder extends RecyclerView.ViewHolder { protected FrameLayout mapContainer; public MapViewHolder(View v){ super(v); view = v; mapContainer = (FrameLayout) v.findViewById(R.id.mapContainer); } } private void bindMapRow(final MapViewHolder holder,int position) { MessageData message = (MessageData) messagesList.get(position); LocationData location = message.getLocation(); FrameLayout view = holder.mapContainer; FrameLayout frame = new FrameLayout(context); if (message.getIdMap() != 0) { frame.setId(message.getIdMap()); } else { message.setIdMap(generateViewId()); frame.setId(message.getIdMap()); messagesList.set(position,message); } int size = context.getResources().getDimensionPixelSize(R.dimen.row_chat_map_size); FrameLayout.LayoutParams layoutParams = new FrameLayout.LayoutParams(size,size); frame.setLayoutParams(layoutParams); view.addView(frame); GoogleMapOptions options = new GoogleMapOptions(); options.liteMode(true); SupportMapFragment mapFrag = SupportMapFragment.newInstance(options); mapFrag.getMapAsync(new MapReadyCallback(location)); FragmentManager fm = activity.getSupportFragmentManager(); FragmentTransaction ft = fm.beginTransaction(); ft.replace(frame.getId(),mapFrag); ft.commit(); }
执行此操作我可以看到显示在我的RecyclerView中的地图,并且所有地图似乎都运行良好.
当我在RecyclerView中向上滚动一段时间然后我又回到地图时会出现问题.
java.lang.IllegalArgumentException: No view found for id 0x1 (unkNown)
for fragment SupportMapFragment{606864b #0 id=0x1}
非常感谢和亲切的问候,
马塞尔.
解决方法
我假设在onBindViewHolder上调用了bindMapRow.
错误的原因IllegalArgumentException:找不到id的视图是在onBindViewHolder期间holder.mapContainer和frame还没有附加到RecyclerView / Activity(因此找不到视图错误).
要在调用FragmentTransaction.replace之前保证视图已附加到RecyclerView / Activity,请转而使用onViewAttachedToWindow.
class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> { ... @Override public void onViewAttachedToWindow(ViewHolder holder) { super.onViewAttachedToWindow(holder); // If you have multiple View Type,check for the correct viewType SupportMapFragment mapFragment = holder.mapFragment; if (mapFragment == null) { mapFragment = SupportMapFragment.newInstance(); mapFragment.getMapAsync(new OnMapReadyCallback() { @Override public void onMapReady(GoogleMap googleMap) { ... } }); } FragmentManager fragmentManager = getSupportFragmentManager(); fragmentManager.beginTransaction().replace(R.id.map,mapFragment).commit(); } }
https://code.luasoftware.com/tutorials/android/supportmapfragment-in-recyclerview/
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。