自定义布局根本不显示 - Android

Custom Layout not Displaying at all - Android

我正在编写代码以便在相机预览中显示自定义视图(绘制圆圈)。它构建良好,没有错误,但问题是自定义视图未显示。 我可能在将自定义视图集成到 Main Activity 或 XML 中时犯了一个错误,但无法弄清楚。需要专家意见,谢谢

Main Activity - Starting camera and integrate Custom view on it

public class AndroidVideoCaptureExample extends Activity {
private Context myContext;
private FrameLayout cameraPreview;
private boolean cameraFront = false;
private int desiredwidth=640, desiredheight=360;
private MyDrawing md;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

    md = (MyDrawing)findViewById(R.id.Drawing);

    myContext = this;
    initialize();
    }
}

CustomView Class - To draw circle on Camera preview

public class MyDrawing extends View {

Canvas canvas;
private static final int DEFAULT_CIRCLE_COLOR = Color.RED;

private int circleColor = DEFAULT_CIRCLE_COLOR;
private Paint paint;

public MyDrawing(Context context) {
    super(context);

    init(context, null);
}



public MyDrawing(Context context, AttributeSet attrs)
{
    super(context, attrs);
    init(context, attrs);
}

private void init(Context context, AttributeSet attrs)
{
    paint = new Paint();
    paint.setAntiAlias(true);
}

@Override
protected void onDraw(Canvas canvas)
{
    super.onDraw(canvas);

    int w = getWidth()/2;
    int h = getHeight()/2;

    int pl = getPaddingLeft();
    int pr = getPaddingRight();
    int pt = getPaddingTop();
    int pb = getPaddingBottom();

    int usableWidth = w - (pl + pr);
    int usableHeight = h - (pt + pb);

    int radius = Math.min(usableWidth, usableHeight) / 2;
    int cx = pl + (usableWidth / 2);
    int cy = pt + (usableHeight / 2);

    paint.setColor(circleColor);
    canvas.drawCircle(cx, cy, radius, paint);
}
}

Layout XML - A Camera Preview with custom preview on it

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="horizontal"
android:baselineAligned="false">

<FrameLayout
    android:id="@+id/camera_preview"
    android:layout_width="match_parent"
    android:layout_height="504dp"
    android:orientation="horizontal">
    <com.javacodegeeks.androidvideocaptureexample.MyDrawing
        android:id="@+id/Drawing"
        android:layout_width="match_parent"
        android:layout_height="534dp"
        android:orientation="horizontal"
       />

</FrameLayout>


</FrameLayout>

你不需要也提供一个onMeasure()方法吗?

编辑: 您正在创建自定义视图,因此您应该告诉 Android 系统如何测量它。

onMeasure() 放入您的 MyDrawing class.

为确保它是问题的原因,请记录这些值:

int w = getWidth()/2;
int h = getHeight()/2;

而不是使用这个:

int w = getWidth()/2;
int h = getHeight()/2;

使用这个:

int w = getMeasuredWidth()/2;
int h = getMeasuredHeight()/2;

在与您类似的情况下,这对我有用。希望对你有帮助。