Android databinding on inner class not updating TextView

后端 未结 1 1387
旧巷少年郎
旧巷少年郎 2021-01-27 11:30

App runs but the TextView doesn\'t get update here is the relevant code.

activity_picker_dashboard.xml



        
相关标签:
1条回答
  • 2021-01-27 11:58

    The problem is in how you're mixing data binding layouts with regular layouts.

    If you want to include a data binding layout from a regular layout, you need to find the root view of the layout and call bind() on it. Maybe something like this:

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    
        setContentView(R.layout.activity_picker_dashboard);
        View bindingRoot = findViewById(R.id.toolbar);
    
        LayoutHeaderBinding binding = LayoutHeaderBinding.bind(bindingRoot);
    
        ProfileResponse.Payload profilePayload = new ProfileResponse.Payload();
        profilePayload.setFirstName("Test");
    
        binding.setProfilePayload(profilePayload);
    }
    

    However, it is better to make your Activity's layout a data binding layout and you won't have to do that extra work:

    <?xml version="1.0" encoding="utf-8"?>
    <layout xmlns:android="http://schemas.android.com/apk/res/android">
        <data>
            <variable
                name="profilePayload"
                type="myms.models.ProfileResponse.Payload"/>
        </data>
        <android.support.constraint.ConstraintLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent">
    
            <!-- Top header -->
    
            <include layout="@layout/layout_header" app:profilePayload="@{profilePayload}" />
    
            <!-- DrawerLayout -->
        </android.support.constraint.ConstraintLayout>
    </layout>
    

    And then your binding code is much simpler and less error prone:

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    
        ActivityPickerDashboardBinding binding = 
            DataBindingUtil.setContentView(this, R.layout.activity_picker_dashboard);
    
        ProfileResponse.Payload profilePayload = new ProfileResponse.Payload();
        profilePayload.setFirstName("Test");
    
        binding.setProfilePayload(profilePayload);
    }
    

    On a different note, I think Android data binding and butterknife have significant overlap in functionality and I would recommend choosing one or the other, but not both.

    0 讨论(0)
提交回复
热议问题