如何在Android中创建键盘监听器?

时间:2014-08-11 04:01:02

标签: android keyboard listener

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

1 个答案:

答案 0 :(得分:0)

为软键盘检测制作课程

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);