【发布时间】:2018-02-13 19:34:42
【问题描述】:
我在使用custom Square Layout 时偶然发现了这个问题:通过扩展 布局并覆盖其onMeasure() 方法以使尺寸= 两者中的较小(高度或宽度)。
以下是自定义布局代码:
public class CustomSquareLayout extends RelativeLayout{
public CustomSquareLayout(Context context) {
super(context);
}
public CustomSquareLayout(Context context, AttributeSet attrs) {
super(context, attrs);
}
public CustomSquareLayout(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
public CustomSquareLayout(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
//Width is smaller
if(widthMeasureSpec < heightMeasureSpec)
super.onMeasure(widthMeasureSpec, widthMeasureSpec);
//Height is smaller
else
super.onMeasure(heightMeasureSpec, heightMeasureSpec);
}
}
自定义方形布局可以正常工作,直到自定义布局超出屏幕范围。但是,应该自动调整到屏幕尺寸的东西不会发生。如下所示,CustomSquareLayout 实际上延伸到屏幕下方(不可见)。我期望onMeasure 处理这个问题,并给出适当的测量值。但事实并非如此。 有趣的地方是,即使CustomSquareLayout 的行为很奇怪,它的子布局都属于始终放置在左侧的方形布局。
<!-- XML for above image -->
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="300dp"
android:text="Below is the Square Layout"
android:gravity="center"
android:id="@+id/text"
/>
<com.app.application.CustomSquareLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="@id/text"
android:background="@color/colorAccent" #PINK
android:layout_centerInParent="true"
android:id="@+id/square"
android:padding="16dp"
>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_centerInParent="true" #Note this
android:background="@color/colorPrimaryDark" #BLUE
>
</RelativeLayout>
</com.app.application.CustomSquareLayout>
</RelativeLayout>
正常情况:(Textview在顶部)
以下是我引用的几个链接:
希望在扩展布局时使用onMeasure或任何其他函数来解决这个问题(这样即使有些扩展了自定义布局,Square属性仍然存在)
编辑 2:我偏爱onMeasure() 或需要提前(渲染之前)确定布局规范(尺寸)的功能。否则在组件加载后更改尺寸很简单,但不需要。
【问题讨论】:
-
在此处链接此issue,因为它是相关的。问题实际上出在父
RelativeLayout上,它不尊重(出于某种原因)我们计算的width & height。尝试将其更改为LinearLayout或FrameLayout它应该可以工作。我还在研究它,但现在没有时间。