Two-way data binding Converter

血红的双手。 提交于 2021-01-29 14:16:43

问题


I'm trying to use a converter from CharArray to String for my password two-way databinding field.

var password = ObservableField<CharArray>()

Following the doc :

public class Converter {
    @InverseMethod("stringToCharArray")
    public static String charArrayToString(
            ClearableEditText view,
            char[] oldValue,
            char[] value
    ){
        return value.toString();
    }

    public static char [] stringToCharArray(
            ClearableEditText view,
            String oldValue,
            String value
    ){
        return value.toCharArray();
    }
}

In XML file I used it like this :

android:text="@={Converter.charArrayToString(viewModel.password)}"

But I still got the bellow exception :

error: Could not find inverse method: public static char[] stringToCharArray(ClearableEditText, char[], java.lang.String)
    public static String charArrayToString(
                         ^   

回答1:


You have to provide BindingAdapter and InverseBindingAdapter for two way data binding. Try using below Binding adapter.

@BindingAdapter("android:text")
public static void bindArrayInText(TextView view, char[] value) {
    view.setText(String.valueOf(value));    
}

@InverseBindingAdapter(attribute = "android:text")
public static char[] getArrayFromText(TextView view) {
    String value = view.getText().toString();

    return value.toCharArray();;
}

And use like

android:text="@={viewModel.password}"



回答2:


This work fine for me, maybe after restarting AS :

public class Converter {
    @InverseMethod("toCharArray")
    public static String toString(char [] value) {
        if(value == null) return "";
        return value.length == 0 ? "" : String.valueOf(value);
    }

    public static char [] toCharArray(String value) {
        if(value == null) return "".toCharArray();
        return value.isEmpty() ? "".toCharArray() : value.toCharArray();
    }
}


来源:https://stackoverflow.com/questions/59644403/two-way-data-binding-converter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!