我想将底部边距设置为等于 View /布局的高度。
<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
//Main layout
<LinearLayout
android:id="@+id/content_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
.
.
.
</LinearLayout>
//Bottom drawer layout
<LinearLayout
android:id="@+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
.
.
.
</LinearLayout>
</FrameLayout>
如何为第二个子元素添加恰好等于其高度的下边距,以便它超出屏幕? 是否可以通过xml属性实现?
最佳答案
您无法获取 xml 中 View 的高度。
您可以使用ViewTreeObserver动态获取 View 的高度,然后您可以设置该 View 的边距。
以下是您可以动态执行的方法:
LinearLayout linearLayout = (LinearLayout) findViewById(R.id.layoutid);
final ViewTreeObserver vto = linearLayout.getViewTreeObserver();
vto.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
@SuppressWarnings("deprecation")
@Override
public void onGlobalLayout() {
//get LayoutWidth and height here
int layoutWidth = linearLayout.getWidth();
int layoutHeight = linearLayout.getHeight();
//set layout margin here
LinearLayout.LayoutParams llp = linearLayout.getLayoutParams();
llp.bottomMargin = layoutHeight;
linearLayout.setLayoutParams(llp);
//Then remove layoutChange Listener
ViewTreeObserver vto = linearLayout.getViewTreeObserver();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
vto.removeOnGlobalLayoutListener(this);
} else {
vto.removeGlobalOnLayoutListener(this);
}
}
});
关于android - 如何设置bottom_margin等于其高度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33936891/