【问题标题】:How can i create a keyboard listener in Android?如何在 Android 中创建键盘监听器?
【发布时间】:2014-10-03 19:59:41
【问题描述】:

我想在键盘出现时更改特定布局的可见性。如何为此创建监听器?

【问题讨论】:

    标签: android keyboard listener


    【解决方案1】:

    为软键盘检测创建一个类

    public class RelativeLayoutThatDetectsSoftKeyboard extends RelativeLayout {
    
        public RelativeLayoutThatDetectsSoftKeyboard(Context context, AttributeSet attrs) 
        {
            super(context, attrs);
        }
    
        public interface Listener
        {
            public void onSoftKeyboardShown(boolean isShowing);
        }
    
        private Listener listener;
    
        public void setListener(Listener listener) 
        {
            this.listener = listener;
        }
    
        @Override
        protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) 
        {
            int height = MeasureSpec.getSize(heightMeasureSpec);
            Activity activity = (Activity)getContext();
            Rect rect = new Rect();
            activity.getWindow().getDecorView().getWindowVisibleDisplayFrame(rect);
            int statusBarHeight = rect.top;
            int screenHeight = activity.getWindowManager().getDefaultDisplay().getHeight();
            int diff = (screenHeight - statusBarHeight) - height;
    
            if (listener != null) 
            {
                listener.onSoftKeyboardShown(diff>128); // assume all soft keyboards are at least 128 pixels high
            }
    
            super.onMeasure(widthMeasureSpec, heightMeasureSpec);       
        }
    }
    

    使用 RelativeLayoutThatDetectsSoftKeyboard 类扩展您的活动并在您的活动中编写以下代码

    // 键盘可见时滚动布局

    RelativeLayoutThatDetectsSoftKeyboard mChkKeyBoradVisibility;
                mChkKeyBoradVisibility = (RelativeLayoutThatDetectsSoftKeyboard)    mTabLogin_Layout.findViewById(your layout id);
                mChkKeyBoradVisibility.setListener(this);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-01-02
      • 1970-01-01
      • 2020-05-30
      • 2021-02-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多