数据绑定不适用于Android中的EditText



我正试图在我的项目中实现一个简单的数据绑定。我正试图从EditText中输入的文本中删除空格,但在编译时失败了。以下是代码。有人能帮忙吗?

自定义BindingAdapter类

public class BindingAdapters {
@BindingAdapter("nospace")
public static void setText(TextView textView, boolean value) {

}
} // I also tried with signature public static void setText(TextView textView, String value)

布局xml

<EditText
android:id="@+id/first_name"
android:layout_height="wrap_content"
android:layout_width="match_parent"
app:layout_constraintTop_toBottomOf="@+id/first_lastname"
app:layout_constraintLeft_toLeftOf="parent"
app:nospace="true" />

碎片

@Override
public View onCreateView(@NonNull LayoutInflater inflater,
@Nullable ViewGroup container,
@Nullable Bundle savedInstanceState ) {
Log.w("MainFragment", "onCreateView...");
binding = DataBindingUtil.inflate(inflater, R.layout.main_fragment, container, false);
MyViewModel mainViewModel = MyViewModel .getInstance();
binding.setMyViewModel(mainViewModel);
return binding.getRoot();
}

ViewModel

public class MyViewModel extends ViewModel {
private static MyViewModel myViewModel;
private User user;
private MyViewModel() {
}
public static MyViewModel getInstance() {
if(myViewModel == null) {
myViewModel = new MyViewModel();
}
return myViewModel;
}
}

我得到的错误是AAPT: error: attribute nospace (aka com.example.portfolio:nospace) not found.

这将为您完成工作。

<EditText
android:id="@+id/first_name"
android:layout_height="wrap_content"
android:layout_width="match_parent"
app:layout_constraintTop_toBottomOf="@+id/first_lastname"
app:layout_constraintLeft_toLeftOf="parent"
app:nospace="@{true}" /> //in databinding you should always use @{}

嗨,伙计们,我完成了整个需求。感谢您的支持。

<EditText
android:id="@+id/first_name"
android:layout_height="wrap_content"
android:layout_width="match_parent"
app:layout_constraintTop_toBottomOf="@+id/first_lastname"
app:layout_constraintLeft_toLeftOf="parent"
app:nospace="@{true}" />    
public class BindingAdapters {

@BindingAdapter("nospace")
public static void setNospace(EditText editText, boolean value) {

if(value) {
editText.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
if(s != null && s.toString().contains(" ")) {
editText.setText(s.toString().replace(" ", ""));
editText.setSelection(editText.getText().length());
}
}
@Override
public void afterTextChanged(Editable s) {
}
});
}
}

你能试试吗

@BindingAdapter("app:nospace")
public static void setText(TextView textView, boolean value) {

}

属性的整个名称需要匹配,因此要么在代码中包含app:,要么在xml中删除app:

最新更新