问题
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