我正在尝试为 Google Cardboard 创建一种 HUD 叠加层。
需要复制 HUD(每只眼睛一个)。一个简单的解决方案是手动将所有 XML 元素复制到另一个视图中,但给它们不同的名称。这感觉像是一种糟糕的方法,因为它涉及大量代码重复。
因此,我为 ViewGroup 提出了以下解决方案,该解决方案应该将所有内容渲染两次:
public class StereoView extends FrameLayout {
private static final String TAG = StereoView.class.getSimpleName();
public StereoView(Context context) {
super(context);
init(context);
}
private void init(Context context) {
testPaint.setColor(Color.RED);
}
private Paint testPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
@Override
protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
super.onLayout(changed, left, top, right/2, bottom);
}
@Override
protected void dispatchDraw(Canvas canvas) {
canvas.save();
canvas.translate(getWidth() / 2, 0);
super.dispatchDraw(canvas);
canvas.restore();
super.dispatchDraw(canvas);
}
public StereoView(Context context, AttributeSet attrs) {
super(context, attrs);
init(context);
}
public StereoView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init(context);
}
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
public StereoView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
init(context);
}
}
第一个问题是 dispatchDraw 或 onDraw 都不会被调用,除非是一两次。当子视图无效时不会调用它。
第二个问题是具有 MATCH_PARENT 的元素的背景呈现在 ViewGroups 内部边界之外:
这种方法是希望太多,还是我想错了?创建一个完全自定义的视图来处理复杂的布局和图像似乎需要做很多工作,而复制我的布局似乎是糟糕的设计。