简体   繁体   中英

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM