我需要创建一个视图占位符:一个不会绘制任何内容但具有相同视图维度的视图。我试图通过这样做来实现这一目标:
public class ViewPlaceHolder extends View {
View target;
public ViewPlaceHolder(View target) {
super(target.getContext());
this.target = target;
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
target.measure(widthMeasureSpec, heightMeasureSpec);
super.onMeasure(
MeasureSpec.makeMeasureSpec(target.getMeasuredWidth(), MeasureSpec.EXACTLY),
MeasureSpec.makeMeasureSpec(target.getMeasuredHeight(), MeasureSpec.EXACTLY));
}
}
到目前为止它没有按预期工作。有什么建议? 非常感谢
PS:我需要一个占位符来在scrollView上制作相同的动画和效果
PPS:补充说明: target.getMeasuredWidth()和target.getMeasuredHeight()的结果是正确的,但ViewPlaceholder有一个完整的随机高度(宽度似乎没问题)
答案 0 :(得分:0)
抱歉,我在布局层次结构上出错了,现在它运行正常!
答案 1 :(得分:0)
如果绘制了目标视图,则可以通过调用getWidth()和getHeight()方法来读取其尺寸。因此,如果这些方法不返回0,则可以在ViewPlaceHolder上应用setLayoutParams。您唯一需要记住的是将放置ViewPlaceHolder的布局。假设它是一个RelativeLayout,你可以在ViewPlaceHolder构造函数体中做这样的事情:
public ViewPlaceHolder(View target) {
super(target.getContext());
this.target = target;
int height = target.getHeight();
int width = target.getWidth();
this.setLayoutParams(new RelativeLayout.LayoutParams(width,height));
this.invalidate();
}