CustomView 未显示在 ScrollView 内

CustomView not showing inside ScrollView

这里是新 Android 程序员。

我正在尝试在 Android 上将 .png 图像显示为位图。我能够显示转换后的图像的唯一方法是使用扩展 View 的自定义 class。但是,我的图像太大而无法完全显示在屏幕上,我希望能够滚动它。但是当我定义一个 ScrollView 并将 CanvasBitmap 放入其中时,我得到一个空白屏幕。我没有运气用布局文件设置它,所以这一切都在 Activity class.

中完成

这是创建 Activity 的地方:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    ScrollView scroll = new ScrollView(this);
    scroll.addView(new CustomView(this));
    setContentView(scroll);
}

这是我的 CustomView class:

private class CustomView extends View{

    public CustomView(Context context) {
        super(context);
    }

    @Override
    protected void onDraw(Canvas canvas){
        Bitmap bitmapMap = BitmapFactory.decodeResource(getResources(),R.drawable.resourceimage);
        canvas.drawBitmap(bitmapMap,0,0,null);
        this.setWillNotDraw(false);
    }
}

如果我在 Activity 中替换这行代码:setContentView(scroll) 通过这一行:setContentView(new CustomView(this)),我可以看到图像,尽管不是整个图像。那么,有没有办法在布局文件中进行设置呢?或者我是否缺少需要在 ScrollView class 中声明的内容?

编辑:我不想使用 ImageView,因为我想更改特定位置的图像,使用位图似乎是通过 x 和 y 坐标实现这一点的最简单方法。

您的自定义视图需要覆盖 onMeasure 方法并正确设置测量的宽度和高度,以便 parent 视图(在本例中为 ScrollView)可以知道多少space 分配给 child.