在Activity中的布局的下方有EditText獲取焦點(diǎn)彈出軟鍵盤的時(shí)候,如果不作處理,軟鍵盤可能會(huì)遮擋輸入框或者一些按鍵,這樣的用戶體驗(yàn)比較差。
這里整理了幾種處理方式,可以使頁面整體上移。并且提供一種個(gè)人比較喜歡的方法。
網(wǎng)上常見的三種:
- 1.修改AndroidManifest.xml文件
Android:windowSoftInputMode="stateVisible|adjustResize"
- 2.在Activity中添加配置
在activity中的onCreate中setContentView之前寫上這個(gè)代碼:
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
其實(shí)第二中方式與第一種是一樣的,只不過放的位置不同而已。
- 3.在布局文件中添加ScrollView
把頂級(jí)的layout替換成ScrollView,或者說在頂級(jí)的Layout上面再加一層ScrollView。
這樣就會(huì)把軟鍵盤和輸入框一起滾動(dòng)了,軟鍵盤會(huì)一直處于底部。
個(gè)人推薦
上面三種都是比較簡(jiǎn)單處理,但靈活性較低。軟鍵盤使整體上移可能造成一些控件上移出屏幕無法展示。以下方式就可以比較靈活的控制底部顯示的控件是什么。
先看下效果圖:
軟鍵盤.gif
將如下方法放到onCreate初始化View之后就可以。
/**
* 1、獲取main在窗體的可視區(qū)域
* 2、獲取main在窗體的不可視區(qū)域高度
* 3、判斷不可視區(qū)域高度
* ①大于180:鍵盤顯示 獲取Scroll的窗體坐標(biāo),算出main需要滾動(dòng)的高度,使scroll顯示。
* ②小于180:鍵盤隱藏
* 該值根據(jù)屏幕可以做出修改,在大屏手機(jī)上可以適當(dāng)?shù)恼{(diào)大,不然會(huì)出現(xiàn)問題。
*
* @param main 根布局
* @param scroll 需要顯示的最下方View
*/
public void addLayoutListener(final View main, final View scroll) {
main.getViewTreeObserver().addOnGlobalLayoutListener(() -> {
Rect rect = new Rect();
main.getWindowVisibleDisplayFrame(rect);
int mainInvisibleHeight = main.getRootView().getHeight() - rect.bottom;
if (mainInvisibleHeight > 180) {
int[] location = new int[2];
scroll.getLocationInWindow(location);
int scrollHeight = (location[1] + scroll.getHeight() + ((RelativeLayout.LayoutParams) scroll.getLayoutParams()).bottomMargin) - rect.bottom;
if (scrollHeight > 0) {
main.scrollTo(0, scrollHeight);
}
} else {
main.scrollTo(0, 0);
}
});
}