gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 01:44:21 25 4
gpt4 key购买 nike

我正在编写代码以便在相机预览中显示自定义 View (绘制圆圈)。它构建良好,没有错误,但问题是自定义 View 未显示。 我可能在将自定义 View 集成到主 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()方法吗?

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

onMeasure() 放入您的 MyDrawing 类中。

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

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

关于android - 自定义布局根本不显示 - Android,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33945341/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com