这里的主要问题是父布局是嵌套 ScrollView ,因此高度必须是换行内容 所以 View 就像第一张图片
what I want is to make the "don't have an account? register" TextView to be at the bottom of the screen so I calculate the height of my phone then the height of layout to subtract to subtract them and assign the result to the top margin of textview
这是我的代码
ViewTreeObserver observer = binding.parentConstraint.getViewTreeObserver();
if (observer.isAlive()) {
observer.addOnGlobalLayoutListener(() -> {
DisplayMetrics displayMetrics = getContext().getResources().getDisplayMetrics();
float parentViewHeightInDP = (int) (binding.parentConstraint.getHeight() / displayMetrics.density);
if (getContext() != null) {
float heightInDP = displayMetrics.heightPixels / displayMetrics.density;
float distanceBetweenLayoutBottomAndParenBottom = heightInDP - parentViewHeightInDP;
if (distanceBetweenLayoutBottomAndParenBottom > 32) {
if (topMargin == 0) {
topMargin = 1;
ConstraintLayout.LayoutParams layoutParams = (ConstraintLayout.LayoutParams) binding.loginTextDontHaveAccount.getLayoutParams();
layoutParams.topMargin = Math.round(distanceBetweenLayoutBottomAndParenBottom);
Handler handler = new Handler();
handler.postDelayed(() -> {
binding.loginTextDontHaveAccount.requestLayout(); },
50);
}
}
但是我得到的结果
so my real question here is why there still some space here, I mean the TextView should be exactly at the bottom
最佳答案
我建议你将 NestedScrollView 设置为 subview 而不是父 View 。 将RelativeLayout设为父级,并使用layout_alignParentBottom将TextView设置在底部。像这样的东西。
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<androidx.core.widget.NestedScrollView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="?android:colorBackground"
android:clickable="true"
android:fillViewport="true"
android:focusable="true">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical">
<ImageView
android:id="@+id/img1"
android:layout_width="wrap_content"
android:layout_height="650dp"
android:background="@mipmap/ic_launcher" />
<ImageView
android:layout_width="match_parent"
android:layout_height="650dp"
android:layout_below="@+id/img1"
android:background="@color/colorPrimary" />
</LinearLayout>
</RelativeLayout>
</androidx.core.widget.NestedScrollView>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true" />
</RelativeLayout>
关于java - 计算我 dp 出错的高度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59283751/