Android Studio中hospitalListAdapter实例化报错及RecyclerView问题求助
解决RecyclerView适配器实例化参数不匹配问题
问题原因
你的hospitalListAdapter构造函数要求传入Context和**ArrayListhospitalActivity中实例化时仅传入了Context,导致参数不匹配,触发报错。
解决方案(二选一即可)
方案一:给适配器添加单参数构造函数
修改hospitalListAdapter.java,新增一个仅接收Context的构造方法,同时保留原有的双参数构造函数以兼容其他场景:
public class hospitalListAdapter extends RecyclerView.Adapter<hospitalListAdapter.ViewHolder> { Context mContext; ArrayList<hospitalListItem> items = new ArrayList<>(); // 新增单参数构造函数 public hospitalListAdapter(Context mContext) { this.mContext = mContext; this.items = new ArrayList<>(); } // 保留原双参数构造函数 public hospitalListAdapter(Context mContext, ArrayList<hospitalListItem> items) { this.mContext = mContext; this.items = items; } // 其余代码不变... }
修改后,原adapter = new hospitalListAdapter(getApplicationContext());代码可正常运行,后续调用addItem添加数据不受影响。
方案二:在Activity中先初始化列表再传入适配器
修改hospitalActivity.java的onCreate方法,先创建空列表,再将Context和列表一起传入适配器:
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_hospital); hospital_list = findViewById(R.id.hospital_list); LinearLayoutManager layoutManager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false); hospital_list.setLayoutManager(layoutManager); // 先初始化空列表 ArrayList<hospitalListItem> hospitalList = new ArrayList<>(); // 传入Context和列表实例化适配器 adapter = new hospitalListAdapter(this, hospitalList); hospital_list.setAdapter(adapter); // 后续添加数据代码保持不变 adapter.addItem(new hospitalListItem(R.drawable.nuribom, "동물병원", "종로구","02-33", "어쩌구저쩌구")); // ... 其他addItem代码 }
小提示
实例化适配器时,建议用this(Activity本身作为Context)代替getApplicationContext(),可避免潜在的内存泄漏风险。
内容的提问来源于stack exchange,提问作者kimzero
相关产品推荐
相关产品推荐

