【发布时间】:2021-04-19 14:39:25
【问题描述】:
当您在 Android Studio 的文本字段中键入输入时,是否有办法在屏幕上自动显示文本?
例如,如果我输入一个数字,它会自动乘以 20,结果会显示在文本字段下方的屏幕上。
【问题讨论】:
标签: android android-studio textview
当您在 Android Studio 的文本字段中键入输入时,是否有办法在屏幕上自动显示文本?
例如,如果我输入一个数字,它会自动乘以 20,结果会显示在文本字段下方的屏幕上。
【问题讨论】:
标签: android android-studio textview
一种简单的方法是使用 Textview 事件侦听器来处理您的操作! 这是你可以做到的。
field1 = (EditText)findViewById(R.id.field2);
field1.addTextChangedListener(new TextWatcher()
{
public void afterTextChanged(Editable s)
{ //Called after the changes have been applied to the text.
//You can change the text in the TextView from this method.
}
public void beforeTextChanged(CharSequence s, int start,
int count, int after) {
//Called before the changes have been applied to the text.
}
public void onTextChanged(CharSequence s, int start,int before, int count) {
TextView.setText("Here is the changing text"+s);
//Similar to the beforeTextChanged method but called after the text changes.
}
});
/* 你可以防止这样的无限循环
@Override
public void afterTextChanged(Editable s) {
if (_ignore)
return;
_ignore = true; // prevent infinite loop
// Change your text here.
// myTextView.setText(myNewText);
_ignore = false; // release, so the TextWatcher start to listen again.
}
*/
【讨论】:
我无法正确理解这个问题,所以这里是两种不同情况的解决方案。
et1.addTextChangedListener(new TextWatcher() {
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
//This method is called to notify you that, within s, the count characters beginning at start have just replaced old text that had length before.
newTextView.text=s.toString;
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
// This method is called to notify you that, within s, the count characters beginning at start are about to be replaced by new text with length after.
}
@Override
public void afterTextChanged(Editable s) {
// This method is called to notify you that, somewhere within s, the text has been changed.
}
});
您可以结合使用 TextWatcher 和 LiveData。 在您的 editText 上放置一个 TextWatcher 并将数据存储在 Livedata 中。 (https://developer.android.com/topic/libraries/architecture/livedata) 然后观察这个 liveData 并相应地更改 Textview。
【讨论】: