android点击打开软键盘,Android中的活动中的软键盘打开和关闭监听器

这仅适用android:windowSoftInputMode于您的活动adjustResize在清单中设置的情况。您可以使用布局侦听器来查看键盘是否调整了活动的根布局。

我为我的活动使用类似下面的基类:public class BaseActivity extends Activity {

private ViewTreeObserver.OnGlobalLayoutListener keyboardLayoutListener = new ViewTreeObserver.OnGlobalLayoutListener() {

@Override

public void onGlobalLayout() {

int heightDiff = rootLayout.getRootView().getHeight() - rootLayout.getHeight();

int contentViewTop = getWindow().findViewById(Window.ID_ANDROID_CONTENT).getTop();

LocalBroadcastManager broadcastManager = LocalBroadcastManager.getInstance(BaseActivity.this);

if(heightDiff <= contentViewTop){

onHideKeyboard();

Intent intent = new Intent("KeyboardWillHide");

broadcastManager.sendBroadcast(intent);

} else {

int keyboardHeight = heightDiff - contentViewTop;

onShowKeyboard(keyboardHeight);

Intent intent = new Intent("KeyboardWillShow");

intent.putExtra("KeyboardHeight", keyboardHeight);

broadcastManager.sendBroadcast(intent);

}

}

};

private boolean keyboardListenersAttached = false;

private ViewGroup rootLayout;

protected void onShowKeyboard(int keyboardHeight) {}

protected void onHideKeyboard() {}

protected void attachKeyboardListeners() {

if (keyboardListenersAttached) {

return;

}

rootLayout = (ViewGroup) findViewById(R.id.rootLayout);

rootLayout.getViewTreeObserver().addOnGlobalLayoutListener(keyboardLayoutListener);

keyboardListenersAttached = true;

}

@Override

protected void onDestroy() {

super.onDestroy();

if (keyboardListenersAttached) {

rootLayout.getViewTreeObserver().removeGlobalOnLayoutListener(keyboardLayoutListener);

}

}}

以下示例活动使用此选项在键盘显示时隐藏视图,并在隐藏键盘时再次显示键盘。

xml布局:<?xml  version="1.0" encoding="utf-8"?>

android:id="@+id/rootLayout"

android:layout_width="match_parent"

android:layout_height="match_parent"

android:orientation="vertical">

android:id="@+id/scrollView"

android:layout_width="match_parent"

android:layout_height="0dp"

android:layout_weight="1"

>

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:orientation="vertical"

>

活动:public class TestActivity extends BaseActivity {

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.test_activity);

attachKeyboardListeners();

}

@Override

protected void onShowKeyboard(int keyboardHeight) {

// do things when keyboard is shown

bottomContainer.setVisibility(View.GONE);

}

@Override

protected void onHideKeyboard() {

// do things when keyboard is hidden

bottomContainer.setVisibility(View.VISIBLE);

}        }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值