简体   繁体   中英

Android data binding not working

I am trying to do a simple test example with Android Data Binding . I only want to show in my fragment the text "test" in the EditText named "title" , but this text is not shown. Here is my code:

TestVM.java

public class TestVM extends BaseObservable {

    public TestVM() {}

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

fr_login.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>

FrLogin.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();
}

...

build.gradle

android {

.....

   dataBinding {
       enabled = true
   }

....
}

you need to set value to your binding

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

Problem with your code is that there is no connection between your model and Fragment .

you have to bind your ViewModel as well. Eg

@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();
}
     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;
      }

You should add this line in build.gradle(:app)

" buildFeatures { viewBinding true } "

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM