`Caused by: java.lang.RuntimeException: view must

如果知道想要什么标签,请告诉我。


Caused by: java.lang.RuntimeException: view must have a tag


__BaseActivity.java


    @Override

    public void setContentView(int layoutResID) {


        mBinding.contentParent.removeAllViews();

        DataBindingUtil.inflate(LayoutInflater.from(this), layoutResID, mBinding.contentParent, true);

        super.setContentView(mBinding.getRoot());

    }

__ChildActivity.java


 @Override

    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        mBinding = DataBindingUtil.setContentView(this, R.layout.my_wallet);

}

错误日志


java.lang.RuntimeException: Unable to start activity ComponentInfo{com.mydev}: java.lang.RuntimeException: view must have a tag

        at <more...>

     Caused by: java.lang.RuntimeException: view must have a tag

        at android.databinding.DataBinderMapperImpl.getDataBinder(DataBinderMapperImpl.java:121)



白衣染霜花
浏览 1028回答 2
2回答

尚方宝剑之说

这通常发生在尝试使用DataBindingUtil.inflate()不支持数据绑定的布局来膨胀时。换句话说,您尝试膨胀的布局的根元素不是<layout>.我在重构Activity以使用数据绑定时遇到了这个问题,并且Activity有多个布局。我成功重构了其中一个布局以将<layout>元素包含在其根部,但我没有重构所有其他布局(其他屏幕密度、语言、模块等的布局)。检查以确保所有可能的匹配布局都配置<layout>为它们的根元素。请参阅此开发人员文档布局和绑定表达式

莫回无

发生此错误的另一个场景是在 RecyclerView 的 ViewHolder 中。避免在 ViewHolder 的绑定方法中初始化绑定实例class BindingAdapter(private val items: List<Any>): RecyclerView.Adapter<BindingHolder>() {&nbsp; &nbsp; &nbsp; override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): BindingHolder {}&nbsp; &nbsp; &nbsp; override fun onBindViewHolder(holder: BindingHolder, position: Int) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;holder.bindItem(items[position])&nbsp; &nbsp; &nbsp; }&nbsp;}class BindingHolder(view: View): RecyclerView.ViewHolder(view) {&nbsp; &nbsp; fun bindItem(item: Any) {&nbsp; &nbsp; &nbsp; &nbsp; //Don't do this&nbsp; &nbsp; &nbsp; &nbsp; val binding = ItemSampleBinding.bind(itemView)&nbsp; &nbsp; }}数据绑定实例应该在 bind 方法之外初始化,因为 ViewHolders 可以被回收,并且在上面的代码中,我们可以尝试从已经绑定的视图创建绑定实例。而是在 ViewHolder 的初始化块中创建绑定实例(这可以在init{}块中或在类声明之后,如下所示)class BindingHolder(view: View): RecyclerView.ViewHolder(view) {&nbsp; &nbsp; val binding = ItemSampleBinding.bind(view)&nbsp; &nbsp; fun bindItem(item: Any) {&nbsp; &nbsp; &nbsp; &nbsp; //Rest of ViewHolder logic&nbsp; &nbsp; &nbsp; &nbsp; //binding.textView.text = "Something nice"&nbsp; &nbsp; }}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java