我有一个自定义的 View
。在 View 的构造函数中,我创建并添加了两个 subview 。但是,使用 LayoutParams.addRule()
会导致一些问题。 CENTER_HORIZONTAL
等规则有效,但当我尝试使用 ABOVE
时, subview 最终高度为 0。
这是我的构造函数中的代码:
setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
mLayoutParams = new LayoutParams(width, height);
mLayoutParams.leftMargin = left;
mLayoutParams.topMargin = top;
mImage = new ImageView(getContext());
mImage.setImageDrawable(getResources().getDrawable(R.drawable.my_image_drawable));
mImage.setScaleType(ScaleType.FIT_XY);
mImage.setId(R.id.my_image_id);
addView(mImage, mLayoutParams);
mText = new TextView(getContext());
mText.setText(R.string.my_text);
mText.setId(R.id.my_text_id);
LayoutParams textParams = new LayoutParams(200, 40);
// textParams.addRule(CENTER_HORIZONTAL, TRUE); //Works
textParams.addRule(ABOVE, mImage.getId()); //Doesn't work
addView(mText, textParams);
如果我用 Device Monitor 检查模拟器上的 View ,我可以看到文本的 layout_height
是 40,但是 top、bottom 和 height 参数都是 0。measuredHeight
似乎与屏幕宽度相同。
- 我在添加规则时做错了什么吗?
- 是否有更好的地方来添加规则?需要先发生什么事吗?
- 还有其他选择吗?使
TextView
的高度为 FILL_PARENT,引力为 BOTTOM,并将其底部边距设置为图像的高度可行,但我需要能够在文本上方添加另一个 View ,这不会不为此工作。
最佳答案
您在代码的哪个位置检查高度?如果它位于 onCreate 或 onCreateView 中的某处,您将不会获得任何信息。布局是一个两次通过的过程,在这两种方法中,两次通过并不完整。
您可能需要使用像这样的“.post”方法在这些方法中获取高度:
myView.post( new Runnable() {
@Override
public void run() {
int height = myView.getHeight();
}
});
runnable 使其在 UI 线程上运行,但它会在两个 channel (测量 channel 和布局 channel )完成后被调用。因此,在不知道测量结果的情况下尝试基于水平中心设置规则将会失败。
关于android - 以编程方式将 ABOVE 添加到 LayoutParams 会导致 View 高度为 0,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18601261/