Android TextWatcher 的 onTextChanged、beforeTextChanged 和 afterTextChanged 之间的差异
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20278382/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Differences between TextWatcher 's onTextChanged, beforeTextChanged and afterTextChanged
提问by Samantha Withanage
In my Android project, I have had to add a TextChangedListener(TextWatcher) to an edit text view. And there are three parts to it:
在我的 Android 项目中,我不得不向编辑文本视图添加一个TextChangedListener(TextWatcher)。它分为三个部分:
onTextChanged()
beforeTextChanged()
afterTextChanged()
onTextChanged()
beforeTextChanged()
afterTextChanged()
What are the differences of these three? I have had to implement a search of a table on the key listener and for my case all these three looked the same. Also they functioned the same. When I input a part of a product name, the table redraws with only those products that contain entered text in it. But I used the afterTextChanged()
part. My code is:
这三者有什么区别?我不得不在关键侦听器上实现对表的搜索,对于我的情况,所有这三个看起来都一样。它们的功能也相同。当我输入产品名称的一部分时,表格会重新绘制仅包含其中包含输入文本的产品。但我使用了afterTextChanged()
部分。我的代码是:
EditProduct.addTextChangedListener(new TextWatcher() {
@Override
public void onTextChanged(CharSequence s, int start, int before,
int count) {
// TODO Auto-generated method stub
// System.out.println("onTextChanged"+s);
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
// TODO Auto-generated method stub
// System.out.println("beforeTextChanged"+s);
}
@Override
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub
// System.out.println("afterTextChanged"+s);
String new_prx = s.toString();
System.out.println(s);
mini_productList = new ArrayList<Product>();
// mini_productList
int count = 0;
if (new_prx.equals("")) {
loadtableProducts(productList);
} else {
for (int i = 0; i < productList.size(); i++) {
if (productList.get(i).getDescription().toString()
.substring(0, (new_prx.length()))
.equalsIgnoreCase(new_prx)) {
mini_productList.add(productList.get(i));
count++;
}
}
loadtableProducts(mini_productList);
}
}
});
So can someone give me an explanation on these three?
那么有人可以给我解释一下这三个吗?
采纳答案by Michael Yaworski
onTextChanged
runs during the text changing.
onTextChanged
在文本更改期间运行。
afterTextChanged
runs immediately after the text is changed.
afterTextChanged
文本更改后立即运行。
beforeTextChanged
runs the instant before the text is changed.
beforeTextChanged
运行文本更改前的瞬间。
Depending on when you want to assign variables or do things, you may want to run the code the instant before the change, or the instant after.
根据您想要分配变量或执行操作的时间,您可能希望在更改前或更改后的瞬间运行代码。
Here is an example of this:
这是一个例子:
String afterTextChanged = "";
String beforeTextChanged = "";
String onTextChanged = "";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
et = (EditText)findViewById(R.id.editText);
et.addTextChangedListener(new TextWatcher() {
@Override
public void onTextChanged(CharSequence s, int st, int b, int c)
{
onTextChanged = et.getText().toString();
}
@Override
public void beforeTextChanged(CharSequence s, int st, int c, int a)
{
beforeTextChanged = et.getText().toString();
}
@Override
public void afterTextChanged(Editable s)
{
afterTextChanged = et.getText().toString();
Toast.makeText(Activity.this, "before: " + beforeTextChanged
+ '\n' + "on: " + onTextChanged
+ '\n' + "after: " + afterTextChanged
,Toast.LENGTH_SHORT).show();
}
});
}
In this case, let's say you changed the text from "h" to "hi", the output would be:
在这种情况下,假设您将文本从“h”更改为“hi”,输出将是:
before: "h"
on: "hi"
after: "hi"
前:“h”
上:“嗨”
后:“嗨”
回答by Suragch
The parameters for beforeTextChanged
and onTextChanged
are a little hard to understand at first. It may be helpful to see them being used in an example. Watch the following demonstration a few times. Pay attention to the counts.
有关参数beforeTextChanged
和onTextChanged
是有点难以在第一理解。在示例中看到它们的使用可能会有所帮助。多看几次下面的演示。注意计数。
- The redhighlight is the old text that is about to be replaced by the green text.
- The greenhighlight is the new text that just replaced the red text.
- 该红色亮点是旧的文本即将由绿色文本替换。
- 该绿色亮点是刚刚更换的红色文字的新文本。
beforeTextChanged
文本更改前
start
is the start index of the red highlighted text (that is about to be deleted)count
is the length of the redhighlighted text (that is about to be deleted)after
is the length of the greenhighlighted text (that is about to be added)
start
是红色高亮文本的起始索引(即将被删除)count
是红色突出显示的文本的长度(即将被删除)after
是绿色突出显示的文本的长度(即将添加)
onTextChanged
onTextChanged
start
is the start index of the green highlighted text (that just got added).
This is the same as thestart
ofbeforeTextChanged
.before
is the length of the redhighlighted text (that just got deleted).
This is the same as thecount
ofbeforeTextChanged
.count
is the length of the greenhighlighted text (that just got added).
This is the same as theafter
ofbeforeTextChanged
.
start
是绿色突出显示的文本(刚刚添加)的起始索引。
这是一样start
的beforeTextChanged
。before
是红色突出显示的文本(刚刚被删除)的长度。
这是一样count
的beforeTextChanged
。count
是绿色突出显示的文本(刚刚添加)的长度。
这是一样after
的beforeTextChanged
。
afterTextChanged
文本更改后
editable
is the editable text from the EditText. You are allowed to change it here. Doing so will trigger all theTextWatcher
events again.- You are not given any information about what was changed. If you want to know, you can set a span in
onTextChanged
and then look up the span here.
editable
是来自 EditText 的可编辑文本。您可以在此处更改它。这样做将TextWatcher
再次触发所有事件。- 您不会获得有关更改内容的任何信息。如果你想知道,你可以在里面设置一个跨度
onTextChanged
,然后在这里查找跨度。
When to use which?
什么时候用哪个?
If you want to observe the changes being made, use beforeTextChanged()
or onTextChanged()
. You are not allowed to change the CharSequence
text in either of these methods, though.
如果您想观察所做的更改,请使用beforeTextChanged()
或onTextChanged()
。但是,您不能CharSequence
在这两种方法中的任何一种中更改文本。
If you want to further modify the text after it was changed, do it in afterTextChanged()
.
如果要在更改后进一步修改文本,请在afterTextChanged()
.
Code
代码
Here is the code if you want to play around with it yourself.
如果你想自己玩,这里是代码。
MainActivity.java
主活动.java
public class MainActivity extends AppCompatActivity {
final static int RED_COLOR = Color.parseColor("#fb7373");
final static int GREEN_COLOR = Color.parseColor("#40de83");
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
EditText editText = findViewById(R.id.editText);
final TextView tvBeforeText = findViewById(R.id.tvBeforeText);
final TextView tvBeforeNumbers = findViewById(R.id.tvBeforeNumbers);
final TextView tvAfterText = findViewById(R.id.tvAfterText);
final TextView tvAfterNumbers = findViewById(R.id.tvAfterNumbers);
editText.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
SpannableString spannableString = new SpannableString(s);
BackgroundColorSpan backgroundSpan = new BackgroundColorSpan(RED_COLOR);
spannableString.setSpan(backgroundSpan, start, start + count, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
tvBeforeText.setText(spannableString);
tvBeforeNumbers.setText("start=" + start + " count=" + count + " after=" + after);
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
SpannableString spannableString = new SpannableString(s);
BackgroundColorSpan backgroundSpan = new BackgroundColorSpan(GREEN_COLOR);
spannableString.setSpan(backgroundSpan, start, start + count, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
tvAfterText.setText(spannableString);
tvAfterNumbers.setText("start=" + start + " before=" + before + " count=" + count);
}
@Override
public void afterTextChanged(Editable s) {
Log.i("TAG", "afterTextChanged: " + s);
}
});
}
}
activity_main.xml
活动_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="5dp">
<EditText
android:id="@+id/editText"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="20sp"
android:text="beforeTextChanged" />
<TextView
android:id="@+id/tvBeforeText"
android:textSize="17sp"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:id="@+id/tvBeforeNumbers"
android:textSize="17sp"
android:text="start=0 count=0 after=0"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="20sp"
android:layout_marginTop="20dp"
android:text="onTextChanged" />
<TextView
android:id="@+id/tvAfterText"
android:textSize="17sp"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:id="@+id/tvAfterNumbers"
android:textSize="17sp"
android:text="start=0 count=0 after=0"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
回答by Jigar Pandya
Android TextChangedListener
is one kind of trigger which is called on text change of an input field.
AndroidTextChangedListener
是一种触发器,它在输入字段的文本更改时调用。
TextChangedListener
has three events.
TextChangedListener
有三个事件。
1.beforeTextChanged :This means that the characters are about to be replaced with some new text. The text is uneditable. This event is used when you need to take a look at the old text which is about to change.
1.beforeTextChanged :这意味着字符将被一些新文本替换。文本不可编辑。当您需要查看即将更改的旧文本时使用此事件。
2.onTextChanged:Changes have been made, some characters have just been replaced. The text is uneditable. This event is used when you need to see which characters in the text are new.
2.onTextChanged:做了改动,只是替换了一些字符。文本不可编辑。当您需要查看文本中哪些字符是新字符时使用此事件。
3.afterTextChanged :The same as above, except now the text is editable. This event is used when you need to see and possibly edit new text.
3.afterTextChanged :同上,除了现在文本是可编辑的。当您需要查看并可能编辑新文本时使用此事件。
回答by Kailash Dabhi
abstract void afterTextChanged(Editable s)
This method is called to notify you that, somewhere within s, the text has been changed.
abstract 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.
abstract 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.
abstract void afterTextChanged(Editable s)
调用此方法是为了通知您,在 s 内的某处,文本已更改。
abstract void beforeTextChanged(CharSequence s, int start, int count, int after)
调用此方法是为了通知您,在 s 内,从 start 开始的 count 个字符即将被长度为 after 的新文本替换。
abstract void onTextChanged(CharSequence s, int start, int before, int count)
调用此方法是为了通知您,在 s 内,从 start 开始的 count 个字符刚刚替换了之前具有 length 的旧文本。
You can more learn here.
回答by Kailash Dabhi
afterTextChanged(Editable s) - This method is called when the text has been changed. Because any changes you make will cause this method to be called again recursively, you have to be watchful about performing operations here, otherwise it might lead to infinite loop.
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. It is an error to attempt to make changes to s from this callback.
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. It is an error to attempt to make changes to s from this callback.
afterTextChanged(Editable s) - 当文本被改变时调用这个方法。因为你所做的任何更改都会导致该方法再次被递归调用,所以在此处执行操作时必须小心,否则可能会导致无限循环。
beforeTextChanged(CharSequence s, int start, int count, int after) - 调用此方法是为了通知您,在 s 内,从 start 开始的 count 个字符即将被长度为 after 的新文本替换。尝试从此回调中更改 s 是错误的。
onTextChanged(CharSequence s, int start, int before, int count) - 调用此方法是为了通知您,在 s 内,从 start 开始的计数字符刚刚替换了之前具有长度的旧文本。尝试从此回调中更改 s 是错误的。