2

我有一个 Android 编程问题。使用下面的代码,我想验证字符串匹配。它验证得很好,但 LogCat 显示 TextWatcher 方法每次击键都会触发两次,我不知道为什么。我希望每次击键只发生一次触发。

你知道它为什么这样做吗?

我认为这可能是因为我更改了文本的颜色,但是在将其注释掉之后并没有什么不同。

LogCat 输出

03-31 03:37:25.269: I/BeforeText(676): Hit 
03-31 03:37:25.269: I/OnText(676): Hit
03-31 03:37:25.269: I/AfterText(676): Hit
03-31 03:37:25.274: I/InvalidText(676): Incorrect Text.
03-31 03:37:25.274: I/Text Value(676): a
03-31 03:37:25.404: I/BeforeText(676): Hit
03-31 03:37:25.404: I/OnText(676): Hit
03-31 03:37:25.404: I/AfterText(676): Hit
03-31 03:37:25.404: I/InvalidText(676): Incorrect Text.
03-31 03:37:25.404: I/Text Value(676): a

活动代码

public void onCreate(Bundle savedInstanceState) {

     //...omitted

    //Create Answer Field
    textField = (EditText)this.findViewById(R.id.textField);

    //Add validation to TextField
    textField.addTextChangedListener(new TextWatcher(){
        public void afterTextChanged(Editable s){

            Log.i("AfterText","Hit");

            if(textField.getText().toString().trim().equalsIgnoreCase("hello")){
                Log.i("ValidText", "Text matched.");

                answerField.setTextColor(Color.GREEN);

            }
            else{
                Log.i("InvalidText", "Incorrect text.");
                Log.i("Text Value", textField.getText().toString());

                textField.setTextColor(Color.RED);

            }
        }

        public void beforeTextChanged(CharSequence s, int start, int count, int after){
            //Do nothing
            Log.i("BeforeText", "Hit");
        }

        public void onTextChanged(CharSequence s, int start, int before, int count){
            //Do nothing
            Log.i("OnText","Hit");

        }
    });
}
4

5 回答 5

3

由于您的问题是针对TextWatcher 的方法,因此每次击键都会触发两次。您已使用 TextWather 对 EditText 进行 Make watch 以进行 Validate String 并设置 Color 。

您可以在此处参考开发人员站点中的 TextWatcher 文档。http://developer.android.com/reference/android/text/TextWatcher.html

当您按下 keystore 时,它​​将以 TextWatcher 方法onTextChanged调用的方式更改 EditText 文本,当您按下 EditText 方法的任何键时,beforeTextChanged这将在我们开始编辑 EditText 时调用。

另一件事是,当您在 EditText 中输入一个字符时,它将调用所有这三种方法Textwather。只是 Call 的顺序不同。并且还引用了这个 SO Question Android TextWatcher.afterTextChanged vs TextWatcher.onTextChanged

所以在 EditText 中为 Text Change 调用两次是没有错的。

希望你能理解。

于 2012-03-31T05:36:17.797 回答
1

Maybe you have two textWatchers, the textField.addTextChangedListener method is called twice.

于 2014-03-24T15:00:51.107 回答
1

我认为这对您没有帮助,但就我而言,它似乎是滑动键盘。

关键是,当滑动尝试提出建议时,onchange 方法似乎被调用了两次(一个来自 EditText,另一个来自滑动键盘)。

我不知道这在您的代码中是否可行,但只需在您的 EditText 上尝试一下,看看会发生什么:

android:inputType="textNoSuggestions"

您可以查看下一个讨论此问题的站点:

http://support.swiftkey.net/forums/116693-2-bug-reports/suggestions/2994580-span-exclusive-exclusive-spans-cannot-have-a-zero-

如果找到解决方案,我将编辑此答案。


编辑


我的结论是,我无法避免中间事件,也无法区分来自用户的真实更改事件或滑动更改事件。

根据您的实际问题,您应该尝试不同的解决方法。一种解决方法可能是将更新的信息保存在 ConcurrentHashMap 中,并在收到事件后 100 毫秒安排任务。同时你应该设置一个“lastModified”日期。

在计划任务中,您应该询问“距离上次更新已过去 100 毫秒?”,如果答案是否定的 --> 什么也不做(这意味着另一个事件已经到达,因此将使用最后一个值执行另一个更新任务)。

伴随所有的 ReentrantLock 来达到原子性。

像这样的东西:

   private final ReentrantLock lock = new ReentrantLock();
    private final ScheduledExecutorService scheduleExecutor = new ScheduledThreadPoolExecutor(1);
    private Date lastModification = null;
    private static final long UPDATE_WINDOW_IN_MILLISECONDS = 100;

protected class UpdateBusinessLogicTask implements Runnable {
    private final String newVal;

    public UpdateBusinessLogicTask(String newVal) {
        super();
        this.newVal = newVal;
    }

    @Override
    public void run() {

        //check current date
        Date now = new Date();
        //get lock to achieve atomicity 
        lock.lock();

        // calculate elapsed time
        long elapsedTime = lastModification.getTime() - now.getTime();

        // free the lock --> you could free the lock after business logic, depends on your scenario
        lock.unlock();

        //if the time is less than the updating window (100 milliseconds)
        if (elapsedTime < (UPDATE_WINDOW_IN_MILLISECONDS - 1)) {
            // DO NOTHING!!
            Log.d("TEST", "Dismiss update "+newVal);
        } else {
            Log.d("TEST", "Updating business with newVal: "+newVal);
            // TODO implement business logic
        }

    }
};

protected void onCreate(Bundle savedInstanceState) {

    EditText view = findViewById(R.id.nameEditText);

    TextWatcher tw = new TextWatcher() {

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            Log.d("TEST", "New text event received, new val: " + s.toString());

            lock.lock();
            lastModification = new Date();

            scheduleExecutor.schedule(new UpdateBusinessLogicTask(s.toString()), UPDATE_WINDOW_IN_MILLISECONDS, TimeUnit.MILLISECONDS);
            lock.unlock();
        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        }

        @Override
        public void afterTextChanged(Editable s) {
        }
    };

}
于 2014-01-27T21:40:57.273 回答
0

您可以使用布尔值。当用户更改文本时设置它,当您的自定义代码触发时重置它。该事件仍会触发两次,但您的代码仅被调用一次。此致。

于 2012-03-31T06:46:01.787 回答
-1

使用它,它可能会帮助您:

myInput.addTextChangedListener(new TextWatcher() {
    boolean mToggle = false;

    public void onTextChanged(CharSequence cs, int s, int b, int c) {}

    public void afterTextChanged(Editable editable) {
        if (mToggle)  
            Toast.makeText(getBaseContext(), "HIT KEY", Toast.LENGTH_LONG).show();
        mToggle = !mToggle;
    }
});
于 2013-07-02T16:14:49.747 回答