效果圖,如上
注意打開應用後,要點擊第一個輸入框,這是因爲先要獲取一次鍵盤的高度,不然首先點擊第二個輸入框,會出現整體佈局擠壓的現象。
佈局文件
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@drawable/splash"
tools:context="org.dync.softkeyboarddemo.MainActivity">
<EditText
android:id="@+id/edt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:hint="獲取鍵盤高度"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="鍵盤高度"
android:id="@+id/text"
android:layout_below="@+id/edt"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<EditText
android:id="@+id/editText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
</RelativeLayout>
在Activity中你只需編寫以下代碼就可實現底部EditText隨鍵盤移動。
MainActivity
SoftKeyboardUtil.observeSoftKeyboard(activity, new SoftKeyboardUtil.OnSoftKeyboardChangeListener() {
@Override
public void onSoftKeyBoardChange(int softKeybardHeight, boolean isShow) {
mSoftKeybardHeight = softKeybardHeight;
isOpen = isShow;
if (isShow) {
onShowKeyboard(softKeybardHeight);
if (isTouch) {//點擊輸入框則不移動控件
editText.animate().translationYBy(-softKeybardHeight).setDuration(duration).start();
}
Log.e("TAG", "isShow--平移高度:" + -mSoftKeybardHeight);
} else {
onHideKeyboard(softKeybardHeight);
editText.animate().translationYBy(softKeybardHeight).setDuration(duration).start();
Log.e("TAG", "isHide--平移高度:" + mSoftKeybardHeight);
isTouch = true;//這裏一定要設置,不然點擊輸入框,控件只會在第一次能移動,之後不會移動了
}
}
}
});
editText.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
Log.e("TAG", "--onTouch--");
if (!isOpen) {//鍵盤沒有打開
if (isTouch) {//這裏是因爲onTouch()方法會不止一次調用,所以用boolean值來使得控件只移動一次
//這裏設爲false目的是防止這裏延時彈出鍵盤會觸發onSoftKeyBoardChange()會再一次調用移動控件的方法
isTouch = false;
//先移動到鍵盤彈出的高度再手動彈出鍵盤,這樣就不會出現擠壓佈局的效果
editText.animate().translationYBy(-mSoftKeybardHeight).setDuration(duration).start();
Log.e("TAG", "平移高度:" + -mSoftKeybardHeight);
new Handler().postDelayed(new Runnable() {
public void run() {
SoftKeyboardUtil.showKeyboard(activity, editText);
}
}, duration);
}
}
return false;//這裏不能返回true,不然焦點不會聚焦到該控件
}
});
...
@Override
protected void onDestroy() {
super.onDestroy();
SoftKeyboardUtil.removeGlobalOnLayoutListener(this);
}
代碼詳情請到github上預覽。
轉載請註明出處,謝謝!