我有一个自定义 View (MyView
),它扩展了 SurfaceView
,我在其中覆盖了 onDraw
方法。我使用自定义构造函数动态创建此 View 的实例:
MyView myView = new MyView(...);
在这个构造函数中,我调用了 super(Context context)
方法。
之后,我将自定义 View 包装在 RelativeLayout
中,如下所示:
((RelativeLayout) findViewById(R.id.container)).addView(myView);
这是我正在使用的布局文件:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<RelativeLayout
android:id="@+id/container"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Test"
android:layout_below="@+id/container"/>
</RelativeLayout>
问题是 TextView
位于屏幕顶部,而不是位于 RelativeLayout
下方(使用 @+id/container
编号)。因为它将没有 android:layout_below
属性。
它的行为就像我的自定义 View (MyView
) 没有设置它的尺寸。我尝试使用 setLayoutParams()
但它没有改变任何东西。
最佳答案
我认为问题在于您的容器 View 在您的自定义 View 添加到它之前已经膨胀和布局,因此高度为 0,因为它没有内容。将其添加到其容器后,将强制重新布局,此时容器要求 subview 测量自身。由于容器的高度是wrap_content
,此时 child 需要报一个具体的高度。我的猜测是您的 MyView
类没有这样做。
要设置 MyView
对象的高度,一件简单的事情就是覆盖并实现 onMeasure()
方法。
关于android - 由于自定义 View ,layout_below 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24715264/