jhoughton
jhoughton

Reputation: 68

CustomView not showing inside ScrollView

New Android programmer here.

I'm trying to display an .png image as a bitmap on Android. The only way I have been able to display the converted image at all is with a custom class that extends View. However, my image is too large to be displayed entirely on the screen and I would like to be able to scroll with it. But when I define a ScrollView and put the Canvas with the Bitmap into it, I get a blank screen. I had no luck setting this up with the layout file, so it is all done in the Activity class.

This is where the Activity is created:

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

And this is my 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);
    }
}

And if I replace this line of code in my Activity: setContentView(scroll) with this line: setContentView(new CustomView(this)), I can see the image, albeit not the entire image. So, is there a way to set this up in the layout files instead? Or is there something I'm missing that I need to declare in the ScrollView class?

EDIT: I would prefer not to use ImageView, because I would like to change the image in specific locations, and using bitmap seemed to be the easiest way to accomplish that, via x and y coordinates.

Upvotes: 1

Views: 1507

Answers (1)

Jin
Jin

Reputation: 6145

Your custom view needs to override the onMeasure method and properly set the measured width and height so that the parent views (in this case the ScrollView) can know how much space to allocate for the child.

Upvotes: 5

Related Questions