editText is not losing focus

2019-02-08 05:51发布

the editText is not losing focus in my app when I click out of it, it has the orange border all time and that black line cursor.. I did this a LinearLayout according to this surrounding the editText: Stop EditText from gaining focus at Activity startup so it doesn't get focus on start of the app..

this is my code:

final EditText et = (EditText)findViewById(R.id.EditText01);

final InputMethodManager imm = (InputMethodManager) getSystemService(
   INPUT_METHOD_SERVICE);

et.setOnClickListener(new View.OnClickListener() {
   public void onClick(View v) {
      imm.showSoftInput(et, InputMethodManager.SHOW_IMPLICIT);
   }
});

et.setOnFocusChangeListener(new View.OnFocusChangeListener() {
   public void onFocusChange(View v, boolean hasfocus) {
      if(hasfocus) {
         imm.showSoftInput(et, InputMethodManager.SHOW_IMPLICIT);
      } else {
         imm.hideSoftInputFromWindow(et.getWindowToken(), 0);
      }
   }
});

But, it doesn't seem to be calling the onFocusChange when I click anywhere outside the editText!

4条回答
太酷不给撩
2楼-- · 2019-02-08 06:17

Override Activity.dispatchTouchEvent():

@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
    if (ev.getAction() == MotionEvent.ACTION_DOWN) {
        View view = getCurrentFocus();
        if (view != null && view instanceof EditText) {
            Rect r = new Rect();
            view.getGlobalVisibleRect(r);
            int rawX = (int)ev.getRawX();
            int rawY = (int)ev.getRawY();
            if (!r.contains(rawX, rawY)) {
                view.clearFocus();
            }
        }
    }
    return super.dispatchTouchEvent(ev);
}

That way, whenever someone clicks anywhere, you have control, and it's at only one point in code.

查看更多
够拽才男人
3楼-- · 2019-02-08 06:23

You can remove the focus from the EditText, by setting the focus to other field by calling the method.

Suppose I have set the focus to back button on click of done button, then call the method on back button inside done button click listener.

And your problem is solved.

back.requestFocusFromTouch();
查看更多
甜甜的少女心
4楼-- · 2019-02-08 06:29

It's simple. You can put the following in LinearLayout or any other else:

android:focusableInTouchMode="true"
查看更多
何必那么认真
5楼-- · 2019-02-08 06:34

Create an onClick listener, possibly in your XML layout to listen for clicks in the background LinearLayout. From here you can call .clearFocus() on your EditText after you make it an instance variable of the activity you are working in.

查看更多
登录 后发表回答