美文网首页
为什么我的页面在PhoneWindow的dispactKeyEv

为什么我的页面在PhoneWindow的dispactKeyEv

作者: 小马要加油 | 来源:发表于2019-07-25 13:37 被阅读0次

    问题

    我在PhoneWindow.java的dispatchKeyEvent里面搞了个配置,企图通过这个配置实时控制硬按键是否可用。
    在普通的activity页面里确实是达到了我要的效果。开心;-)。
    但是。。
    我后面又搞了个页面用WindowManager.addView方式覆盖上来的。
    mWindowManager.addView(mView, mLayoutParams);
    还是老规矩,设置了配置不可用。结果按了音量键,听到了脆耳的来电铃声,崩溃了。

    原因

    我们用Android studio 抓一下layout inspection
    这个是普通activity的view tree

    image.png
    可以看到他的树根是phoneWindow的DecorView,后面才是我们自己在setContentView里传入的layout。
    而用WindowManager.addView的view tree呢,
    image.png
    根布局直接是addView的view。
    所以这也是为什么在 PhoneWindow不能拦截按键事件的原因。
    对于想深入了解PhoneWindow的可以看下这个。https://www.jianshu.com/p/e42b638944ae

    解决

    这条路走不通了,那怎么解决呢?
    自定义view,在dispatchKeyEvent里返回true表示当前view能处理该点击事件,不需要派发到子view。

    public class InterceptedKeyLinearLayout extends LinearLayout {
        private static final String TAG =  InterceptedKeyLinearLayout.class.getSimpleName();
        public InterceptedKeyLinearLayout(Context context) {
            super(context);
        }
    
        public InterceptedKeyLinearLayout(Context context, @Nullable AttributeSet attrs) {
            super(context, attrs);
        }
    
        @Override
        public boolean dispatchKeyEvent(KeyEvent event) {
            Log.d(TAG, "dispatchKeyEvent: prevent the key in this page "+event.toString());
            return true;
        }
    }```
    
    
    

    相关文章

      网友评论

          本文标题:为什么我的页面在PhoneWindow的dispactKeyEv

          本文链接:https://www.haomeiwen.com/subject/qqgcrctx.html