safeUnbox() cannot be inverted

前端 未结 4 851
孤独总比滥情好
孤独总比滥情好 2021-01-06 05:15

I\'m trying to eliminate all the warnings of my Android application and one of them is this:

viewModel.value is a boxed field but needs to be un-boxed

4条回答
  •  野趣味
    野趣味 (楼主)
    2021-01-06 05:49

    I haven't worked with Android Architecture Components or with the Data Binding libraries in this particular way, but I think I can still help.

    Within your XML, you've got this:

    android:checked="@={viewModel.value}"
    

    The system is giving you a warning because it wants you to know that in the case where viewModel.value is null, it's going to do something special (behave as though it were false instead, presumably). It does this via the safeUnbox() method.

    To solve the warning, it's suggesting making the safeUnbox() call explicit. You can't do that because there's no "inverse" of safeUnbox() to go back from boolean to Boolean.

    But it doesn't sound like you have to use safeUnbox(); you could create your own method that converts Boolean to boolean, and then you could use the suggested annotation to declare which method will convert back from boolean to Boolean.

    public class MyConversions {
    
        @InverseMethod("myBox")
        public static boolean myUnbox(Boolean b) {
            return (b != null) && b.booleanValue();
        }
    
        public static Boolean myBox(boolean b) {
            return b ? Boolean.TRUE : Boolean.FALSE;
        }
    }
    

    Now you can change your XML to:

    android:checked="@={com.example.stackoverflow.MyConversions.myUnbox(viewModel.value)}"
    

    I hope this helps. If it turns out that I'm way off-base, let me know; I'd love to learn more about this topic.

    Most of what I have in this answer I learned from https://medium.com/google-developers/android-data-binding-inverse-functions-95aab4b11873

提交回复
热议问题