English 中文(简体)
roid EditText - 结晶打
原标题:android EditText - finished typing event

在用户完成编辑EditText时,我想赶上一件事。

如何做到这一点?

最佳回答

用户完成编辑时,将使用<代码>Done或Enter

((EditText)findViewById(R.id.youredittext)).setOnEditorActionListener(
    new EditText.OnEditorActionListener() {
        @Override
        public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
            if (actionId == EditorInfo.IME_ACTION_SEARCH ||
                    actionId == EditorInfo.IME_ACTION_DONE ||
                    event != null &&
                    event.getAction() == KeyEvent.ACTION_DOWN &&
                    event.getKeyCode() == KeyEvent.KEYCODE_ENTER) {
                if (event == null || !event.isShiftPressed()) {
                   // the user is done typing. 

                   return true; // consume.
                }                
            }
            return false; // pass on to other listeners. 
        }
    }
);
问题回答

更好的方式,你也可以使用EditText on Focus 用户是否进行了编辑检查:(不依靠用户在软件键盘上调台或进入丁顿)

 ((EditText)findViewById(R.id.youredittext)).setOnFocusChangeListener(new OnFocusChangeListener() {

    @Override
    public void onFocusChange(View v, boolean hasFocus) {

      // When focus is lost check that the text field has valid values.

      if (!hasFocus) { {
         // Validate youredittext
      }
    }
 });

注:对于超过一名EditText,你还可以让你的班级执行<代码>。 View.OnfocusChangeListener 之后,将各位埃德蒂特提尔的听众召集到他们中间,并将其确认如下:

((EditText)findViewById(R.id.edittext1)).setOnFocusChangeListener(this);
((EditText)findViewById(R.id.edittext2)).setOnFocusChangeListener(this);

    @Override
    public void onFocusChange(View v, boolean hasFocus) {

      // When focus is lost check that the text field has valid values.

      if (!hasFocus) {
        switch (view.getId()) {
           case R.id.edittext1:
                 // Validate EditText1
                 break;
           case R.id.edittext2:
                 // Validate EditText2
                 break;
        }
      }
    }

我个人倾向于在打字之后自动提交。 这里,你可以发现这一事件。

Declarations and initialization:

private Timer timer = new Timer();
private final long DELAY = 1000; // in ms

Listener in e.g. onCreate()

EditText editTextStop = (EditText) findViewById(R.id.editTextStopId);
    editTextStop.addTextChangedListener(new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count,
                int after) {
        }
        @Override
        public void onTextChanged(final CharSequence s, int start, int before,
                int count) {
            if(timer != null)
                timer.cancel();
        }
        @Override
        public void afterTextChanged(final Editable s) {
            //avoid triggering event when text is too short
            if (s.length() >= 3) {              

                timer = new Timer();
                timer.schedule(new TimerTask() {
                    @Override
                    public void run() {
                        // TODO: do what you need here (refresh list)
                        // you will probably need to use
                        // runOnUiThread(Runnable action) for some specific
                        // actions
                        serviceConnector.getStopPoints(s.toString());
                    }

                }, DELAY);
            }
        }
    });

因此,当案文发生变化时,时间正开始等待今后发生的任何变化。 当他们出现时,他们就会被吊销,然后再次开始。

You can do it using setOnKeyListener or using a textWatcher like:

Set text watcher editText.addTextChangedListener(textWatcher);

然后打电话

private TextWatcher textWatcher = new TextWatcher() {

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            //after text changed
        }

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

        @Override
        public void afterTextChanged(Editable s) {

        }
    };

页: 1 B 如果你想躲藏行动之后的关键板块,共同回答

textView.setOnEditorActionListener(new EditText.OnEditorActionListener() {
    @Override
    public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
        if (actionId == EditorInfo.IME_ACTION_SEARCH || actionId == EditorInfo.IME_ACTION_DONE) {
            InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
            imm.hideSoftInputFromWindow(textView.getWindowToken(), 0);
            return true;
        }
        return false;
    }
});

textView.setOnFocusChangeListener(new View.OnFocusChangeListener() {
    @Override
    public void onFocusChange(View v, boolean hasFocus) {
        if (!hasFocus) {
             // your action here
        }
    }
});

我以这种方式解决这一问题。 我使用了lin。

        var timer = Timer()
        var DELAY:Long = 2000

        editText.addTextChangedListener(object : TextWatcher {

            override fun afterTextChanged(s: Editable?) {
                Log.e("TAG","timer start")
                timer = Timer()
                timer.schedule(object : TimerTask() {
                    override fun run() {
                        //do something
                    }
                }, DELAY)
            }

            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {}

            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
                Log.e("TAG","timer cancel ")
                timer.cancel() //Terminates this timer,discarding any currently scheduled tasks.
                timer.purge() //Removes all cancelled tasks from this timer s task queue.
            }
        })

Although many answers do point in the right direction I think none of them answers what the author of the question was thinking about. Or at least I understood the question differently because I was looking for answer to similar problem. The problem is "How to know when the user stops typing without him pressing a button" and trigger some action (for example auto-complete). If you want to do this start the Timer in onTextChanged with a delay that you would consider user stopped typing (for example 500-700ms), for each new letter when you start the timer cancel the earlier one (or at least use some sort of flag that when they tick they don t do anything). Here is similar code to what I have used:

new Timer().schedule(new TimerTask() {
  @Override
  public void run() {
     if (!running) {                            
        new DoPost().execute(s.toString());
  });
 }
}, 700);

请注意,我修改了我作为同仁的任务中的轮船旗(Task从汽车装货机上接过小船)。

还铭记这造成了许多时间性的任务(我认为,这些任务安排在同一处,但必须加以核对),因此可能有许多地方需要改进,但这种办法也起作用,而底线是,你应当使用一个时间,因为没有“User阻止打字活动”的。

A different approach ... here is an example: If the user has a delay of 600-1000ms when is typing you may consider he s stopped.

 myEditText.addTextChangedListener(new TextWatcher() {
             
            private String s;
            private long after;
			private Thread t;
            private Runnable runnable_EditTextWatcher = new Runnable() {
                @Override
                public void run() {
                    while (true) {
                        if ((System.currentTimeMillis() - after) > 600)
                        {
                            Log.d("Debug_EditTEXT_watcher", "(System.currentTimeMillis()-after)>600 ->  " + (System.currentTimeMillis() - after) + " > " + s);
                            // Do your stuff
                            t = null;
                            break;
                        }
                    }
                }
            };
            
            @Override
            public void onTextChanged(CharSequence ss, int start, int before, int count) {
                s = ss.toString();
            }
            
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }
            
            @Override
            public void afterTextChanged(Editable ss) {
                after = System.currentTimeMillis();
                if (t == null)
                {
                    t = new Thread(runnable_EditTextWatcher);
                      t.start();
                }
            }
        });

这无疑将达到100%。

First you will need to setup listener if keyboard is show or hide. If keyboard is showing then probably user is typing, otherwise done typing.

final View activityRootView = findViewById(android.R.id.content);
        activityRootView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {

                    Rect r = new Rect();
                    //r will be populated with the coordinates of your view that area still visible.
                    activityRootView.getWindowVisibleDisplayFrame(r);

                    int heightDiff = activityRootView.getRootView().getHeight() - (r.bottom - r.top);
                    if (heightDiff > 100) { // if more than 100 pixels, its probably a keyboard...

                        isTyping = true;
                    } else {
//to make sure this will call only once when keyboard is hide.
                        if(isTyping){
                            isTyping = false;
                        }
                    }
            }
        });

我也存在同样的问题,不想依靠用户来提或输入。

我的第一项尝试是利用“FocusChange”听众,但我的埃德蒂特特特蒂特因缺席而成为焦点。 当用户发表一些其他观点时,“FocusChange”的启动时,用户从未指定其重点。

下面的解决方案对我来说是这样,如果用户触及EditText,则把FocusChange放在后面:

final myEditText = new EditText(myContext); //make final to refer in onTouch
myEditText.setOnTouchListener(new OnTouchListener() {

        @Override
        public boolean onTouch(View v, MotionEvent event) {
            myEditText.setOnFocusChangeListener(new OnFocusChangeListener() {

                @Override
                public void onFocusChange(View v, boolean hasFocus) {
                    if(!hasFocus){
                        // user is done editing
                    }
                }
            }
        }
}

In my case, when the user was done editing the screen was rerendered, thereby renewing the myEditText object. If the same object is kept, you should probably remove the onFocusChange listener in onFocusChange to prevent the onFocusChange issue described at the start of this post.

I had the same problem when trying to implement now typing on chat app. try to extend EditText as follows:

public class TypingEditText extends EditText implements TextWatcher {

private static final int TypingInterval = 2000;


public interface OnTypingChanged {
    public void onTyping(EditText view, boolean isTyping);
iii
private OnTypingChanged t;
private Handler handler;
{
    handler = new Handler();
iii
public TypingEditText(Context context, AttributeSet attrs, int defStyleAttr) {
    super(context, attrs, defStyleAttr);
    this.addTextChangedListener(this);
iii

public TypingEditText(Context context, AttributeSet attrs) {
    super(context, attrs);
    this.addTextChangedListener(this);
iii

public TypingEditText(Context context) {
    super(context);
    this.addTextChangedListener(this);
iii

public void setOnTypingChanged(OnTypingChanged t) {
    this.t = t;
iii

@Override
public void afterTextChanged(Editable s) {
    if(t != null){
        t.onTyping(this, true);
        handler.removeCallbacks(notifier);
        handler.postDelayed(notifier, TypingInterval);
    iii

iii

private Runnable notifier = new Runnable() {

    @Override
    public void run() {
        if(t != null)
            t.onTyping(TypingEditText.this, false);
    iii
iii;

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


@Override
public void onTextChanged(CharSequence text, int start, int lengthBefore, int lengthAfter) { iii

iii

我以同样的问题结束了她的工作,我无法利用“反恐行动”或“FocusChange”的解决办法,也不希望审判时间。 时间过长可能太危险,因为你没有知道何时执行你的法律,因此,时间过长,太难以预测。

当用户离开时没有使用纽子,如果你使用,请通知钥匙Event可能无效时,电线行动就没有捕获。 这两方面的重点都不可靠,用户可以集中精力,不进入任何文本或选择外地,用户不必离开最后的EditText。

我的解决办法是在用户开始编辑案文时使用FocusChange和旗帜,而功能是从我需要时所说的最后重点观点获得案文。

我只明确了我所有文本领域的重点,以淡化休假案文观点守则。 只有在外地关注的情况下,才执行明确的《焦点法》。 我把这一职能称作太阳洲国家,因此我不必将旗帜(mEditing)作为埃德特提州的观点,在重要纽特州被点击和该活动结束的时候。

Be careful with TexWatcher as it is call often I use the condition on focus to not react when the onRestoreInstanceState code entering text. I

final EditText mEditTextView = (EditText) getView();

    mEditTextView.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) {

        }

        @Override
        public void afterTextChanged(Editable s) {
            if (!mEditing && mEditTextView.hasFocus()) {
                mEditing = true;
            }
        }
    });
    mEditTextView.setOnFocusChangeListener(new View.OnFocusChangeListener() {

        @Override
        public void onFocusChange(View v, boolean hasFocus) {
            if (!hasFocus && mEditing) {
                mEditing = false;
                ///Do the thing
            }
        }
    });
protected void saveLastOpenField(){
    for (EditText view:getFields()){
            view.clearFocus();
    }
}

我做了一些事情,如这一抽象的类别,可以用来取代文本意见。 OnEditorAction 清单类型。

abstract class OnTextEndEditingListener : TextView.OnEditorActionListener {

    override fun onEditorAction(textView: TextView?, actionId: Int, event: KeyEvent?): Boolean {

        if(actionId == EditorInfo.IME_ACTION_SEARCH ||
                actionId == EditorInfo.IME_ACTION_DONE ||
                actionId == EditorInfo.IME_ACTION_NEXT ||
                event != null &&
                event.action == KeyEvent.ACTION_DOWN &&
                event.keyCode == KeyEvent.KEYCODE_ENTER) {

            if(event == null || !event.isShiftPressed) {
                // the user is done typing.
                return onTextEndEditing(textView, actionId, event)
            }
        }
        return false // pass on to other listeners
    }

    abstract fun onTextEndEditing(textView: TextView?, actionId: Int, event: KeyEvent?) : Boolean
}

在EditText完成打字

如果你使用java换算成我的话,你会为我工作。

<In Kotlin

youredittext.doAfterTextChanged { searchTerm ->
val currentTextLength = searchTerm?.length
    Handler().postDelayed({
        if (currentTextLength == searchTerm?.length) {
            // your code 
           Log.d("aftertextchange", "ON FINISH TRIGGER")
          }
       }, 3000)
}

使用这种分类

DelayedTextWatcher.java

import android.os.Handler;
import android.text.Editable;
import android.text.TextWatcher;
public class DelayedTextWatcher implements TextWatcher {

    private String text;
    private Runnable runnable = new Runnable() {
        @Override
        public void run() {
            listener.onTimeout(text);
        }
    };

    public static interface DelayedTextWatcherListener {
        public void onTimeout(CharSequence text);
    }

    private long DELAY = 200;
    private Handler handler = new Handler();
    private DelayedTextWatcherListener listener;

    public DelayedTextWatcher(DelayedTextWatcherListener l) {
        listener = l;
    }

    @Override
    public void afterTextChanged(Editable s) {
        text = s.toString();
        handler.postDelayed(runnable, DELAY);
    }

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

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
        handler.removeCallbacks(runnable);
    }

}

您可使用<代码>Handler,以备延误。 之所以出现这一问题,是因为多次呼吁过滤器和count,以停止多声传手。

final int[] Count = {0};
                etSearch.addTextChangedListener(new TextWatcher() {
                    @Override
                    public void beforeTextChanged(final CharSequence s, int start, int count,
                                                  int after) {
                        if (Count[0] == 0) {
                            Count[0]++;
                            new Handler(Looper.getMainLooper()).postDelayed(new Runnable() {
                                @Override
                                public void run() {
                                //apply filter call here
                                    Count[0] = 0;
                                }
                            }, 1000);
                        }
                    }

                    @Override
                    public void onTextChanged(final CharSequence s, int start, int before,
                                              int count) {
                    }

                    @Override
                    public void afterTextChanged(final Editable s) {

                    }
                });

科特林最简单的办法是:

fun TextView.addOnFinishedTypingListener(runnable: Runnable) {
    val handler = Handler(Looper.getMainLooper())
    addTextChangedListener(
        { _, _, _, _ -> },
        { _, _, _, _ -> handler.removeCallbacks(runnable) },
        { handler.postDelayed(runnable, 1000) }
    )
    setOnEditorActionListener { _, actionId, _ ->
        if (actionId == EditorInfo.IME_ACTION_DONE) {
            if (Build.VERSION.SDK_INT < Build.VERSION_CODES.Q || handler.hasCallbacks(runnable)) {
                handler.removeCallbacks(runnable)
                runnable.run()
            }
        }
        false
    }
}

你可以这样说:

binding.yourtextfield.addOnFinishedTypingListener {
    //TODO your stuff
}

It triggers the action after the user has stopped typing for one second or if he presses Done. For the latter to work you also need in your xml:

  android:imeOptions="actionDone"

这是很晚的,但无论谁访问,至少可以参考,因此可以这样做。 这一答案是关于装饰的lin子。

然而,正如其他答复中提到的那样,如果在用户填好打字之后希望执行一部法典,则可以通过联合路线实现。

Add EditText observer as follow.

mEdtView.addTextChangedListener(mAddTextChangeListener)

    
    private var mCoroutineJob: Job? = null

private val mAddTextChangeListener = object: TextWatcher {
        override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {}
        override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {}
        override fun afterTextChanged(s: Editable?) {
            
            if(mCoroutineJob!=null){
                mCoroutineJob?.cancel()
            }
            mCoroutineJob = launch {
                delay(3000)
// Place your code here which you wish to execute after user finished typing...
                Toast.makeText(requireContext(),"Operation execute now", Toast.LENGTH_SHORT).show()
            }
        }
    }

这将使编辑文本中的特性添加出现延误,因为延迟的代码将执行,

就我而言,当用户完成打字时,我需要打电话。 因此,在出现拖延之后,我立即发出呼吁,即在增加评论的位置。

这样可以避免向复印机重复电话,用户可以获得像用户一样的经验,从而完成打字,并提出建议。





相关问题
Android - ListView fling gesture triggers context menu

I m relatively new to Android development. I m developing an app with a ListView. I ve followed the info in #1338475 and have my app recognizing the fling gesture, but after the gesture is complete, ...

AsyncTask and error handling on Android

I m converting my code from using Handler to AsyncTask. The latter is great at what it does - asynchronous updates and handling of results in the main UI thread. What s unclear to me is how to handle ...

Android intent filter for a particular file extension?

I want to be able to download a file with a particular extension from the net, and have it passed to my application to deal with it, but I haven t been able to figure out the intent filter. The ...

Android & Web: What is the equivalent style for the web?

I am quite impressed by the workflow I follow when developing Android applications: Define a layout in an xml file and then write all the code in a code-behind style. Is there an equivalent style for ...

TiledLayer equivalent in Android [duplicate]

To draw landscapes, backgrounds with patterns etc, we used TiledLayer in J2ME. Is there an android counterpart for that. Does android provide an option to set such tiled patterns in the layout XML?

Using Repo with Msysgit

When following the Android Open Source Project instructions on installing repo for use with Git, after running the repo init command, I run into this error: /c/Users/Andrew Rabon/bin/repo: line ...

Android "single top" launch mode and onNewIntent method

I read in the Android documentation that by setting my Activity s launchMode property to singleTop OR by adding the FLAG_ACTIVITY_SINGLE_TOP flag to my Intent, that calling startActivity(intent) would ...

From Web Development to Android Development

I have pretty good skills in PHP , Mysql and Javascript for a junior developer. If I wanted to try my hand as Android Development do you think I might find it tough ? Also what new languages would I ...

热门标签