我正在尝试用Android Data Binding
做一个简单的测试示例。我只想在我的片段中显示名为"test"
的{{1}}中的文字EditText
,但此文字未显示。这是我的代码:
TestVM.java
"title"
fr_login.xml
public class TestVM extends BaseObservable {
public TestVM() {}
@Bindable
public String getText() {
return "test";
}
}
FrLogin.java
<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>
的build.gradle
@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();
}
...
答案 0 :(得分:7)
您需要为绑定设置值
FrLoginBinding binding = DataBindingUtil.inflate(inflater, R.layout.fr_login, container, false);
binding.setTest(new TestVM());
您的代码存在问题,即您的模型与Fragment
之间没有任何关联。
答案 1 :(得分:6)
您还必须绑定type
。 E.g
ViewModel
答案 2 :(得分:0)
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;
}