在一般登錄界面,軟鍵盤彈出時(shí)會(huì)遮擋登錄按鈕,網(wǎng)上的解決方法一般都是設(shè)置WindowSoftInputMode和scrollview嵌套,但無(wú)法達(dá)到我想要的效果。
下面這種方法能夠解決:
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
init();
addLayoutListener(rootView, bottomView);
}
/**
* @param rootView 根布局
* @param bottomView 需要顯示的最下方View,
*/
public void addLayoutListener(View rootView, View bottomView) {
rootView.getViewTreeObserver().addOnGlobalLayoutListener(() -> {
Rect rect = new Rect();
rootView.getWindowVisibleDisplayFrame(rect);//獲取rootView的可視區(qū)域
int invisibleHeight = rootView.getRootView().getHeight() - rect.bottom;//獲取rootView的不可視區(qū)域高度
if (invisibleHeight > 150) { //鍵盤顯示
int[] location = new int[2];
bottomView.getLocationInWindow(location); //獲取bottomView的坐標(biāo)
int scrollHeight = (location[1] + bottomView.getHeight()) - rect.bottom;//算出需要滾動(dòng)的高度
if (scrollHeight != 0) {//防止界面元素改變調(diào)用監(jiān)聽(tīng),使界面上下跳動(dòng),如驗(yàn)證碼倒計(jì)時(shí)
rootView.scrollTo(0, scrollHeight);
}
} else {
rootView.scrollTo(0, 0);
}
});
}