有朋友提到軟鍵盤遮擋布局的問題,說網上找了很多資料都未能解決,下面我來總結一下那些事,有些內容也是從網友那里學來的,但是我都會自己驗證正確了才會貼出來。
首先來分析下我們常見的遮擋問題有哪些(本次所說遮擋問題的控件都是在軟鍵盤彈出的范圍內)。1.點擊輸入框彈出軟鍵盤時,遮擋本輸入框,2.點擊輸入框,輸入框跟隨軟鍵盤自動上移時其他不該移動的內容也跟隨上移,比如ActionBar。3.類似於登陸界面的2個以上的輸入框,點擊第一個進行輸入的時候,它之下的控件不會跟隨上移。
目前就這幾個常見的類型,后續有其他特殊案例可留言再進行補充解決。下面我們逐步解決這三個問題,第一個,這個不用管,因為系統默認點擊輸入框進行輸入的時候會把當前輸入框自動上移,這時候就會引起第二個問題,當他上移的時候,會把它之上的內容一起上移效果如下:
這個時候我們只需要在其中需要上移的內容嵌套在ScrollView中就行了,比如我們上圖的內容將如下紅線框中的內容嵌套到ScrollView中就沒問題了:
親測有效,如果你的沒有效果,那么請嘗試一下設置ScrollView的相關屬性。注意如果要設置android:windowSoftInputMode請不要使用adjustPan值,具體含義在本文最后將作出說明。
第三個問題,當我們點擊輸入用戶名的輸入框時,這時候我們其實也希望軟鍵盤同時將用戶名輸入框和密碼輸入框同時頂到上面去,系統默認是只滿足將獲取輸入焦點的用戶名輸入框頂上去,所以我們要進行相關的處理:基本思路如下,我們通過控制ScrollView的滑動位置來控制顯示區域,並且我們要知道當屬性android:windowSoftInputMode設置成adjustResize的時候,軟鍵盤彈出時Activity會重繪並且他的Activity布局的底部就是軟鍵盤的頂部,這個可以自行測試,接下來我們就知道,我們將需要彈上去的整體都放在ScrollView中,當軟鍵盤彈出時,我們設置ScrollView滑動到底部位置,這樣就能達到效果了,代碼如下:
<com.lvyerose.softtest.KeyboardLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/root_view" android:layout_width="match_parent" android:layout_height="match_parent"> <ScrollView android:id="@+id/scrollView" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_alignParentBottom="true"> <RelativeLayout android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_alignParentBottom="true" android:layout_alignParentLeft="true" android:gravity="center"> <ImageView android:id="@+id/top_img" android:layout_width="match_parent" android:layout_height="160dp" android:layout_marginTop="32dp" android:src="@drawable/bg" /> <EditText android:id="@+id/id_input_name" android:layout_width="180dp" android:layout_height="wrap_content" android:layout_below="@+id/top_img" android:layout_centerHorizontal="true" android:layout_marginTop="32dp" android:hint="請輸入用戶名" /> <EditText android:id="@+id/id_input_password" android:layout_width="180dp" android:layout_height="wrap_content" android:layout_below="@+id/id_input_name" android:layout_centerHorizontal="true" android:hint="請輸入密碼" android:inputType="number" /> </RelativeLayout> </ScrollView> </com.lvyerose.softtest.KeyboardLayout>
其中的KeyboardLayout自定義布局不用管,它是繼承RelativeLayout並添加了監聽軟鍵盤彈出和隱藏的,只是這里用不上,你們測試的時候可以直接使用RelativeLayout即可。在Activity中對第一個輸入框進行監聽:
editTextName.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { changeScrollView(); return false; } });
用於滑動控制ScrollView的方法如下,注意使用延遲回調是因為第一時間軟鍵盤彈出需要短暫的時間,這時候去設置ScrollView時布局還沒有完全重繪完成,也就不會有滑動效果,只有延遲之后就是估量布局穩定了的時候再進行ScrollView上滑才會有效果,這個地方使用過ScrollView的控制滑動的童鞋就應該遇到過!
/** * 100毫秒之后使ScrollView指向底部 */ private void changeScrollView(){ new Handler().postDelayed(new Runnable() { @Override public void run() { scrollView.scrollTo(0, scrollView.getHeight()); } }, 100); }
通過上面的設置就可以完成如登陸界面一樣的效果,讓你需要的整體一起滑動到軟鍵盤的上面而不被遮擋。
之前提到了關於軟鍵盤設置的屬性android:windowSoftInputMode,下面提供倆個博客地址,有需要進一步了解的同學可以去看看:
如果還有未知的情況需要的可以留言!謝謝觀賞~~~