下面代码中Log打印的displayHeight是窗口可视区域的高度,因为style设置的windowNoTitle为true,所以这个高度和通过setContentView设置的布局的可见高度是相同的,所以也可以认为是R.layout.activity_measure_soft_key的可见高度。
Log中的parentHeight是视图的根元素的高度,根元素是一个FrameLayout,只有一个子元素,就是平时在onCreate方法中设置的setContentView。
Log中的softKeyHeight就是计算出的软键盘的高度,是通过根视图高度减去窗口可见高度得到。
对应Activity文件
public class MeasureSoftKeyActivity extends AppCompatActivity {
public static String TAG = "TranslucentActivityTAG";
private ConstraintLayout constraintLayout;
private ViewGroup parentContent;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_measure_soft_key);
constraintLayout = findViewById(R.id.constraint_layout);
parentContent = findViewById(android.R.id.content);
parentContent.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
Rect r = new Rect();
parentContent.getWindowVisibleDisplayFrame(r);
int displayHeight = r.bottom - r.top;
Log.v(TAG, "displayHeight:" + displayHeight);
int parentHeight = parentContent.getHeight();
Log.v(TAG, "parentHeight:" + parentHeight);
int softKeyHeight = parentHeight - displayHeight;
Log.v(TAG, "softKeyHeight:" + softKeyHeight);
}
});
}
}
AndroidManifest.xml
在无Title样式下,通过r.bottom - r.top得到的高度是准确的可见高度。软键盘未弹起时与android.R.id.content对应的布局的高度相同。
<activity android:name=".activity.MeasureSoftKeyActivity"
android:theme="@style/MeasureSoftKeyAppTheme">
</activity>
设置无Title样式
<style name="MeasureSoftKeyAppTheme" parent="AppTheme">
<!-- Customize your theme here. -->
<item name="android:windowNoTitle">true</item>
<item name="windowNoTitle">true</item>
</style>
layout布局:
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/constraint_layout">
<EditText
android:id="@+id/et_input"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:layout_constraintBottom_toBottomOf="parent"/>
</android.support.constraint.ConstraintLayout>
Log:
V/TranslucentActivityTAG: displayHeight:1013
V/TranslucentActivityTAG: parentHeight:1848
V/TranslucentActivityTAG: softKeyHeight:835