如何在Fragment中使用数据绑定

如何在Fragment中使用数据绑定

本文介绍了如何在Fragment中使用数据绑定的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试遵循Google官方文档 https://developer.android中的数据绑定示例.com/tools/data-binding/guide.html

I'm trying to follow data-binding example from official google doc https://developer.android.com/tools/data-binding/guide.html

除了我要对片段而不是活动应用数据出价.

except that I'm trying to apply data-biding to a fragment, not an activity.

我当前在编译时遇到的错误是

the error I'm currently getting when compiling is

Error:(37, 27) No resource type specified (at 'text' with value '@{marsdata.martianSols}.

onCreate片段如下:

@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    MartianDataBinding binding = MartianDataBinding.inflate(getActivity().getLayoutInflater());
    binding.setMarsdata(this);
}

片段的

onCreateView看起来像这样:

onCreateView for fragment looks like this:

@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    return inflater.inflate(R.layout.martian_data, container, false);
}

我的布局文件中的片段部分如下所示:

and parts of my layout file for fragment looks like this:

<?xml version="1.0" encoding="utf-8"?>

<layout xmlns:android="http://schemas.android.com/apk/res/android">
    <data>
        <variable
            name="marsdata"
            type="uk.co.darkruby.app.myapp.MarsDataProvider" />
    </data>
...

        <TextView
            android:layout_height="wrap_content"
            android:layout_width="wrap_content"
            android:text="@{marsdata.martianSols}"
        />

    </RelativeLayout>
</layout>

我怀疑MartianDataBinding不知道应该绑定哪个布局文件-因此出错.有什么建议吗?

my suspicion is that MartianDataBinding doesn't know which layout file it's supposed to be bound with - hence the error. Any suggestions?

推荐答案

数据绑定实现必须在片段的onCreateView方法中,删除在OnCreate方法中存在的所有数据绑定,您的onCreateView应该看起来像这样:

The data binding implementation must be in the onCreateView method of the fragment, delete any data Binding that exist in your OnCreate method,your onCreateView should look like this:

public View onCreateView(LayoutInflater inflater,
                         @Nullable ViewGroup container,
                         @Nullable Bundle savedInstanceState) {
    MartianDataBinding binding = DataBindingUtil.inflate(
            inflater, R.layout.martian_data, container, false);
    View view = binding.getRoot();
    //here data must be an instance of the class MarsDataProvider
    binding.setMarsdata(data);
    return view;
}

这篇关于如何在Fragment中使用数据绑定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-28 21:40