Android軟鍵盤監聽KeyboardWatcher
阿新 • • 發佈:2018-10-31
轉載請標明出處:http://blog.csdn.net/wu_wxc/article/details/53705322
本文出自【吳孝城的CSDN部落格】
在如登入介面上當輸入框獲得焦點時,為了將輸入框顯示出來,不被軟鍵盤遮住,我們可以監聽軟鍵盤的顯示與關閉來實現
首先在build.gradle中配置依賴
compile 'com.azimolabs.keyboardwatcher:keyboardwatcher:0.1.3'
佈局是一個圖片和一個輸入框
MainActivity.java
package cn.wuxiaocheng.keyboardwatcher;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import com.azimolabs.keyboardwatcher.KeyboardWatcher;
public class MainActivity extends AppCompatActivity implements KeyboardWatcher.OnKeyboardToggleListener {
private ImageView img;
private KeyboardWatcher mKeyboardWatcher;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
img = (ImageView) findViewById(R.id.img);
initKeyWatch();
}
// 實現未實現的方法
@Override
public void onKeyboardShown(int keyboardSize) {
img.setVisibility(View.GONE);
}
// 實現未實現的方法
@Override
public void onKeyboardClosed() {
img.setVisibility(View.VISIBLE);
}
// 初始化軟鍵盤監聽
private void initKeyWatch() {
mKeyboardWatcher = new KeyboardWatcher(this);
mKeyboardWatcher.setListener(this);
}
}
然後在AndroidManifest.xml中新增android:windowSoftInputMode=”“配置
<activity android:name=".MainActivity"
android:windowSoftInputMode="adjustResize">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
如果沒有在AndroidManifest.xml裡做相應配置,會報如下錯誤
Caused by: java.lang.IllegalArgumentException: Activity MainActivity should have windowSoftInputMode=”adjustResize”to make KeyboardWatcher working. You can set it in AndroidManifest.xml