效果图:
代码:
public class MainActivity extends AppCompatActivity implements ViewTreeObserver.OnGlobalLayoutListener {
private ImageView logoImg;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
logoImg = findViewById(R.id.logo_img);
}
@Override
protected void onResume() {
super.onResume();
getWindow().getDecorView().getViewTreeObserver().addOnGlobalLayoutListener(this);
}
@Override
protected void onPause() {
super.onPause();
getWindow().getDecorView().getViewTreeObserver().removeGlobalOnLayoutListener(this);
}
@Override
public void onGlobalLayout() {
int screenHeight = logoImg.getRootView().getHeight();//获取根布局高
Rect keyRect = new Rect();
logoImg.getWindowVisibleDisplayFrame(keyRect);//获取当前窗口可视区域大小
int keyShowHeight = screenHeight - keyRect.bottom;
if (keyShowHeight > 0) {
Toast.makeText(this, "键盘显示", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, "键盘隐藏", Toast.LENGTH_SHORT).show();
}
}
}
布局文件就一个图片和一个EditText,这里就不贴出了,关键是代码
int screenHeight = logoImg.getRootView().getHeight();//获取根布局高
Rect keyRect = new Rect();
logoImg.getWindowVisibleDisplayFrame(keyRect);//获取当前窗口可视区域大小
int keyShowHeight = screenHeight - keyRect.bottom;