android 監聽 soft keyboard打開與關閉



首先在manifest.xml文件中將相應的activity屬性中加入android:windowSoftInputMode="adjustResize" 參數。

下一步就是在layout resize的時候加入相應的listener,可惜android沒有提供相應的api,我們只能用自己的方式來監聽這個事件

代碼如下:


public class MyLayout extends LinearLayout {

public MyLayout(final Context context, final AttributeSet attrs) {
super(context, attrs);
}

public MyLayout(Context context) {
super(context);
}

private OnSoftKeyboardListener onSoftKeyboardListener;

@Override
protected void onMeasure(final int widthMeasureSpec, final int heightMeasureSpec) {
if (onSoftKeyboardListener != null) {
final int newSpec = MeasureSpec.getSize(heightMeasureSpec);
final int oldSpec = getMeasuredHeight();
// If layout became smaller, that means something forced it to resize. Probably soft keyboard :)
if (oldSpec > newSpec){
onSoftKeyboardListener.onShown();
} else {
onSoftKeyboardListener.onHidden();
}
}
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}

public final void setOnSoftKeyboardListener(final OnSoftKeyboardListener listener) {
this.onSoftKeyboardListener = listener;
}

// Simplest possible listener :)
public interface OnSoftKeyboardListener {
public void onShown();
public void onHidden();
}
}


That's about it. Of course you need to use your layout (MyLayout) in your code/xml for it to work. And example from activity:


((MyLayout)findViewById(R.id.layout)).setOnSoftKeyboardListener(newOnSoftKeyboardListener() {
@Override
public void onShown() {
// Do something here
}
@Override
public void onHidden() {
// Do something here
}
});



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章