gpt4 book ai didi

android - findViewById 用于我创建的自定义 View

转载 作者:行者123 更新时间:2023-11-29 00:05:13 25 4
gpt4 key购买 nike

我是 android 开发的新手。

我构建了一个 MarakableImageView,用于通过点击图像在图像上绘制圆圈。

public class MarkableImageView extends ImageView {
ArrayList<Marker> mMarkers;

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

@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
Paint paint = new Paint();
paint.setColor(Color.RED);
paint.setStyle(Paint.Style.FILL_AND_STROKE);
for(Marker m : mMarkers){
// TODO: Draw the marker
canvas.drawCircle(m.x, m.y, 3, paint);
}

}

public boolean onTouchEvent(MotionEvent e) {
if (e.getAction() == MotionEvent.ACTION_DOWN) {
mMarkers.add(new Marker(e.getX(), e.getY()));
invalidate();
return true;
}
return false;
}

public void reset() {
mMarkers.clear();
invalidate();
}

// this class will be visible only inside MarkableImageView
private class Marker {
public float x;
public float y;
// you might want to add other properties, for example
// if you need to have different types of markers

public Marker(float x, float y) {
this.x = x;
this.y = y;
}
}
}

并在我使用过的代码中使用它:

is = getContentResolver().openInputStream(selectedImageUri);
MarkableImageView iv = (MarkableImageView) findViewById(R.id.imageView);
Bitmap bmp = BitmapFactory.decodeStream(is);
iv.setImageBitmap(bmp);

我的问题出现在上面第二个代码部分的第二行,因为在 content_main.xml 中,imageView 显示为 ImageView 而不是 MarkableImageView。

我需要修复什么?

最佳答案

My problem occurs in the second line of the second code section above, because in content_main.xml imageView appears as ImageView and not MarkableImageView.

你必须在你的 xml 中声明它,指定你的类的完全限定路径(看看 here )。例如。

<com.example.customviews.MarkableImageView

请注意您的ArrayList<Marker> mMarkers;永远不会实例化。这将使您的应用程序崩溃 NPE

关于android - findViewById 用于我创建的自定义 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34343071/

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