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

时间:2015-11-26 18:51:14

标签: android android-layout android-studio android-custom-view

我正在浏览代码,以便在相机预览上显示自定义视图(圆圈绘制)。它构建良好,没有错误,但问题是自定义视图没有显示。 我可能在主要活动或XML中集成自定义视图时出错,但无法弄清楚。需要专家意见,谢谢

  

主要活动 - 启动相机并在其上集成自定义视图

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类 - 在相机预览上绘制圆圈

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);
}
}
  

布局XML - 带有自定义预览的相机预览

<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>

2 个答案:

答案 0 :(得分:1)

您是否还需要提供onMeasure()方法?

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

onMeasure()放入MyDrawing班级。

要确定问题的原因,请记录以下值:

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

答案 1 :(得分:0)

而不是使用它:

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

使用此:

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

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

相关问题