0

Ok this should be a fun one...

We have a Fragment with a viewmodel: RoomFragment.java, fragment_room.xml, and RoomViewModel.java The Fragment's view is binded to the xml, and the viewModel is available in that xml.

So far so good.

Now...I'm creating a new custom view object: CustomView.kt ...and I want to use this custom view within a parent view (fragment_room.xml) AND be able to bind buttons in my CustomView to methods in the parent's viewModel.

For some pseudocode... (fragment_room.xml)

<ParentView>
    <data>
        <variable viewModel>
    </data>

    <Button
        android:onClick:"@{viewModel::onSomeButtonClick}"
        />

    <com.my.CustomView
        android:width
        android:height
        app:myCustomAction:@{viewModel::onClickCustomButton}"
        />
</ParentView>

(This is currently set to a string...but changing it doesn't change anything.)

<declare-styleable name="CustomView">
    <attr name="app:myCustomAction" format="string"/>
</declare-styleable>

The error app:myCustomAction:@{viewModel::onClickCustomButton}" gives me Could not resolve viewModel::onClickCustomButton as a listener.

Any ideas? Or if there's a better way...?

André
  • 380
  • 4
  • 9
  • the closest thing I've found is this post > https://stackoverflow.com/questions/36580316/android-declare-styleable-method-attributes however that 1) is not about databinding but about reflection, and 2) doesn't work as-is since the `DeclaredOnClickListener` looks in that view's class for the method...so I'd have to do some magic to make it look in a different class for the function. – André Nov 06 '20 at 16:19
  • You could consider passing the entire ViewModel to your CustomView and get the Listener then instead of trying to only pass the listener. – Tobi Nov 13 '20 at 18:46

0 Answers0