android 动态监听整个布局的焦点变化

1.初始化OnGlobalFocusChangeListener
private ViewTreeObserver.OnGlobalFocusChangeListener focusChangeListener = new ViewTreeObserver.OnGlobalFocusChangeListener() {
        @Override
        public void onGlobalFocusChanged(View oldFocus, View newFocus) {
                if ((oldFocus != null)) {
                    Log.d("info", "oldFocus ==" + oldFocus+" id:"+oldFocus.getId());
                }
                if (newFocus != null) {
                    Log.d("info", "newFocus ==" + newFocus+" id:"+newFocus.getId());
                    //如果得到的newFocusId为基础控件的id,则调用它的getParent()可以获取父控件的id,可依次类推
                    Log.d("info", "newFocus ==" + newFocus+" id:"+newFocus.getId()+" parentId:"+newFocus.getParent().getParent());
                }
            if (mAccesslayout.hasFocus()){
                //Log.d(TAG, "focus enter");
                mAccessTitle.setEllipsize(TextUtils.TruncateAt.MARQUEE);//获取焦点时title滚动显示
            }else{
                //Log.d(TAG, "focus lost");
                mAccessTitle.setEllipsize(TextUtils.TruncateAt.END);//失去焦点时title末尾显示省略号
            }
        }
    };
2.添加OnGlobalFocusChangeListener的监听,mAccesslayout代表想监听的布局
@Override
    public void onResume() {
        super.onResume();
        mAccesslayout.getViewTreeObserver().addOnGlobalFocusChangeListener(focusChangeListener);
    }
3.移除OnGlobalFocusChangeListener的监听
@Override
    public void onPause() {
        super.onPause();
        mAccesslayout.getViewTreeObserver().removeOnGlobalFocusChangeListener(focusChangeListener);
    }
4.举例:mAccesslayout代表想监听的整个布局,当Web Access或SSH Access获取焦点后,title可滚动显示
601
失去焦点
602
获取焦点,title滚动
0

留下评论