我不太确定为什么我的自定义 View 组不会在其 subview (线性布局)中渲染 TextView :
这是我的 View 组代码:
import android.content.Context;
import android.graphics.Color;
import android.graphics.RectF;
import android.view.View;
import android.view.ViewGroup;
public class noteLayout extends ViewGroup {
float leftOrientationSize = 0;
float rightOrientationSize=0;
public noteLayout(Context activityContext)
{
super(activityContext);
}
@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
int numberOfChild = getChildCount();
for (int i = 0;i<numberOfChild;i++){
View childView = getChildAt(i);
float childHeight = (float) childView.getMeasuredHeight();
float childWidth = (float) childView.getMeasuredWidth();
RectF rect = new RectF();
rect.bottom = 300;
rect.top = 20;
rect.left = 50;
rect.right = (getWidth()/2)-20;
childView.layout((int) rect.left, (int) rect.top, (int) rect.right, (int) rect.bottom);
}
}
}
我创建了一个简单的线性布局,里面有一个 TextView 。该文件为 xml 格式,名为 test3。
此外,以下代码用于将 test3 布局添加到自定义 View 组中。
private void layoutNoteView() {
noteLayout noteLayout = new noteLayout(this);
noteLayout.addView((View) getLayoutInflater().inflate(R.layout.test3,null));
RelativeLayout.LayoutParams noteLayoutParams = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
noteLayoutParams.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
noteLayoutParams.addRule(RelativeLayout.ALIGN_PARENT_START);
}
noteLayoutParams.addRule(RelativeLayout.BELOW, R.id.StartRelativeLayout);
relativeLayoutMain.addView(noteLayout,noteLayoutParams);
}
我的问题是我不太确定为什么我的自定义 View 组甚至不会在线性布局内渲染 TextView 。它渲染的只是 test3 布局文件的线性布局。我非常想弄清楚如何让 TextView 得到渲染。
请注意,如果我单独有一个 TextView 而不将其放入线性布局中,我的自定义 View 组会完美地呈现该 TextView 。仅当我将其放在布局中然后将其放入自定义 View 组布局中时才会发生这种情况。
最佳答案
将 ViewGroup
绘制到屏幕需要 2 个步骤:
测量
ViewGroup
及其子项以获得正确的大小将 children 布置在他们应该画自己的地方
测量是为了找出 View 有多大。测量后,您应该得到一个值,表明 View 需要有多大。
布局实际上是为 View 分配位置和大小。您可以但不应该忽略测量返回的值。将其变大通常没有问题,但将其变小很可能会切断某些内容。
通过不调用您的ViewGroup
子级的测量方法,他们不知道它们有多大,或者它们将获得多少空间。
只需将 TextView
布局到完整宽度/高度即可正确渲染,因为它有足够的大小来正确渲染。
在没有事先测量的情况下布局 LinearLayout
,LinearLayout
本身对其子级一无所知。出于布局目的,它正在查看 getMeasuredHeight()
但在那里找不到任何值,因此无法布局其子项。这就是为什么 LinearLayout
会“绘制”但它的子级不会。
始终包含测量值,或从您想要扩展的现有布局进行扩展,例如FrameLayout
如果您只想自己设置位置,但子项可能会重叠。如果不进行测量,有些事情会很好地工作,而另一些则不会,而这大多只是为了找出什么会有效而进行的试验和错误。
关于java - 为什么我的自定义 View 组不会在线性布局中显示 TextView ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35821028/