Android数据绑定不工作

63lcw9qa  于 2022-12-21  发布在  Android
关注(0)|答案(4)|浏览(162)

我正在尝试用Android Data Binding做一个简单的测试示例。我只想在我的片段中显示名为"title"EditText中的文本"test",但是这个文本没有显示。下面是我的代码:

测试虚拟机.java

public class TestVM extends BaseObservable {

    public TestVM() {}

    @Bindable
    public String getText() {
        return "test";
    }
}

fr登录名.xml

<layout xmlns:android="http://schemas.android.com/apk/res/android">

<data>
    <variable
        name="test"
        type="de.theappguys.templateandroid.viewmodel.TestVM"/>
</data>

<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@android:color/transparent"
    >

 <TextView
            android:id="@+id/title"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentLeft="true"
            android:layout_marginTop="20dp"
            android:text="@{test.text}"
            android:textSize="22sp"
            android:textStyle="bold"
            android:textColor="@android:color/black"
            />

</RelativeLayout>
</layout>

法语登录.java

@EFragment
public class FrLogin extends Fragment {

...

 @Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    FrLoginBinding binding = DataBindingUtil.inflate(inflater, R.layout.fr_login, container, false);

    return binding.getRoot();
}

...

生成分级

android {

.....

   dataBinding {
       enabled = true
   }

....
}
kmbjn2e3

kmbjn2e31#

您需要为绑定设置值

FrLoginBinding binding = DataBindingUtil.inflate(inflater, R.layout.fr_login, container, false);
binding.setTest(new TestVM());

您的代码的问题是您的模型和Fragment之间没有连接。

qvsjd97n

qvsjd97n2#

你还必须绑定你的ViewModel

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    FrLoginBinding binding = DataBindingUtil.inflate(inflater, R.layout.fr_login, container, false);
    binding.setTest(new TestVM());
    return binding.getRoot();
}
2q5ifsrm

2q5ifsrm3#

您应该在build.gradle(:app)中添加此行
“构建功能{视图绑定为真}“

lo8azlld

lo8azlld4#

private Context mContent;

     @Override
      public View onCreateView(LayoutInflater inflater, ViewGroup container,
          Bundle savedInstanceState) {

        FragmentBrandBinding binding = FragmentBrandBinding.inflate(inflater, container, false);
        View view = binding.getRoot();
        mContent = view.getContext();
        return view;
      }

相关问题