EditText上,明确重点触摸外 [英] EditText, clear focus on touch outside

查看:167
本文介绍了EditText上,明确重点触摸外的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的布局包含的ListView SurfaceView 的EditText 。当我点击的EditText ,它接收焦点和屏幕键盘弹出。当我点击某处的的EditText ,它仍然具有焦点外(它不应该)。 我想我可以设置 OnTouchListener 的在布局中的其他意见和手动清除的EditText 的焦点。但似乎太hackish的...

My layout contains ListView, SurfaceView and EditText. When I click on the EditText, it receives focus and the on-screen keyboard pops up. When I click somewhere outside of the EditText, it still has the focus (it shouldn't). I guess I could set up OnTouchListener's on the other views in layout and manually clear the EditText's focus. But seems too hackish...

我也有同样的情况在其他的布局 - 列表视图与不同类型的项目,其中有一些的EditText 的里面。他们的行为就像我上面写的。

I also have the same situation in the other layout - list view with different types of items, some of which have EditText's inside. They act just like I wrote above.

的任务是使的EditText 失去焦点,当用户触摸它以外的东西。

The task is to make EditText lose focus when user touches something outside of it.

我已经看到了类似的问题在这里,但没有找到任何解决办法...

I've seen similar questions here, but haven't found any solution...

推荐答案

我尝试了所有这些解决方案。 edc598的是最接近的工作,但触摸事件并没有对其他查看触发由包含在布局。如果有人需要这样的行为,这是我最后做:

I tried all these solutions. edc598's was the closest to working, but touch events did not trigger on other Views contained in the layout. In case anyone needs this behavior, this is what I ended up doing:

我创建了一个(不可见的)的FrameLayout 所谓的 touchInterceptor 的作为最后查看的布局,使其覆盖一切(修改您还可以使用 RelativeLayout的作为父布局,给的 touchInterceptor FILL_PARENT 属性)。然后,我用它来拦截触摸并确定触摸是在顶部的的EditText 与否:

I created an (invisible) FrameLayout called touchInterceptor as the last View in the layout so that it overlays everything (edit: you also have to use a RelativeLayout as the parent layout and give the touchInterceptor fill_parent attributes). Then I used it to intercept touches and determine if the touch was on top of the EditText or not:

FrameLayout touchInterceptor = (FrameLayout)findViewById(R.id.touchInterceptor);
touchInterceptor.setOnTouchListener(new OnTouchListener() {
    @Override
    public boolean onTouch(View v, MotionEvent event) {
        if (event.getAction() == MotionEvent.ACTION_DOWN) {
            if (mEditText.isFocused()) {
                Rect outRect = new Rect();
                mEditText.getGlobalVisibleRect(outRect);
                if (!outRect.contains((int)event.getRawX(), (int)event.getRawY())) {
                    mEditText.clearFocus();
                    InputMethodManager imm = (InputMethodManager) v.getContext().getSystemService(Context.INPUT_METHOD_SERVICE); 
                    imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
                }
            }
        }
        return false;
    }
});

返回FALSE,让触摸操作告吹。

Return false to let the touch handling fall through.

这是哈克,但它是为我工作的唯一的事。

It's hacky, but it's the only thing that worked for me.

这篇关于EditText上,明确重点触摸外的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆