1. No view found for id Fragment
由于业务需要,项目中做了一个fragment的组件专门用来执行选图显示上传功能模块,由于表单需要,需要将组件放在RecycleView(该方法不推荐,但是奈何短期要解决问题不方便大改),在嵌入过程中报错No view found for id Fragment ,查询了源代码,大概分析了一下,可能是recyclerView的复用问题。
出错源代码:
if (!mFragment.mRestored) {
String resName;
try {
resName = mFragment.getResources().getResourceName(mFragment.mContainerId);
} catch (Resources.NotFoundException e) {
resName = "unknown";
}
throw new IllegalArgumentException("No view found for id 0x"
+ Integer.toHexString(mFragment.mContainerId) + " ("
+ resName + ") for fragment " + mFragment);
}
解决方案:
// 每个fragment设置独立的ID,同时ID仅赋值一次,保证id 唯一,此代码在convert holder中
if (!item.isGenerated) {
view.id = View.generateViewId()
item.isGenerated = true
}
//监听view 的Attach 方法,当attach 的时候添加时候执行commit方法
view.addOnAttachStateChangeListener(object : View.OnAttachStateChangeListener {
override fun onViewAttachedToWindow(v: View?) {
view.removeOnAttachStateChangeListener(this)
//添加fragment
val fragment = PhotoFragment()
fragment!!.setmMaxCount(5)
val bundle = Bundle()
bundle.putInt(PhotoFragment.ACTION, item.type)
bundle.putString(Constants.NAME, item.desc)
bundle.putParcelableArrayList(Attachment.ATTACHMENTS, item.attachList)
item.fragment!!.arguments = bundle
val transaction = fragmentManager.beginTransaction()
transaction.replace(
view.id,
item.fragment!!
)
if (!item.fragment!!.isAdded) {
transaction.commitNowAllowingStateLoss()
}
}
override fun onViewDetachedFromWindow(v: View?) {
}
})