Dennis Brunek
Dennis Brunek

Reputation: 3

Xamarin c# Cant get a image to work in a LinearLayout which is in a ScrollView

I have this problem in xamarin, where i make a custom view called picview which simply makes a bitmap and draws it and my activity class DatLocPage i want to have this picture in a LinearLayout which is in a Scrollview, but it doesnt seem to work. It does work when i just use SetContentView for the picview alone.

My code for the class DatLocPage is:

[Activity(Label = "")] class DatlocPage : Activity { protected override void OnCreate(Bundle b) { base.OnCreate(b);

        ScrollView upmenu = new ScrollView(this);
        upmenu.SetBackgroundColor(Color.White);

        LinearLayout menu = new LinearLayout(this);
        menu.Orientation = Orientation.Vertical;
        menu.SetBackgroundColor(Color.White);

        upmenu.AddView(menu);

        picview pic = new picview(this);
        menu.AddView(pic);

        Button Back = new Button(this); Back.Text = "Back"; Back.Click += 
        klikback; menu.AddView(Back);

        this.SetContentView(upmenu);
    }

and for my custom view picview it is:

class picview : View
{
    Bitmap Plaatje;
    public picview(Context c) : base(c)
    {
        this.SetBackgroundColor(Color.White);
        Plaatje = BitmapFactory.DecodeResource(c.Resources, Resource.Drawable.watch);
    }
    protected override void OnDraw(Canvas canvas)
    {
        base.OnDraw(canvas);
        Paint verf = new Paint();
        canvas.DrawBitmap(Plaatje, 0, 0, verf);
    }
}

Upvotes: 0

Views: 40

Answers (1)

Cheesebaron
Cheesebaron

Reputation: 24470

You are missing a bunch of LayoutParameters on your views, which tell them how big they should be.

Take a look at this modified code:

ScrollView upmenu = new ScrollView(this);
upmenu.SetBackgroundColor(Color.White);
upmenu.LayoutParameters = 
    new ViewGroup.LayoutParams(
        ViewGroup.LayoutParams.MatchParent, 
        ViewGroup.LayoutParams.MatchParent);

LinearLayout menu = new LinearLayout(this);
menu.Orientation = Orientation.Vertical;
menu.SetBackgroundColor(Color.White);
menu.LayoutParameters =
    new ViewGroup.LayoutParams(
        ViewGroup.LayoutParams.MatchParent,
        ViewGroup.LayoutParams.MatchParent);

upmenu.AddView(menu);

var pic = new picview(this);
pic.LayoutParameters =
    new ViewGroup.LayoutParams(
        ViewGroup.LayoutParams.MatchParent,
        200);
menu.AddView(pic);

Button Back = new Button(this); 
Back.Text = "Back";
Back.LayoutParameters =
    new ViewGroup.LayoutParams(
        ViewGroup.LayoutParams.MatchParent,
        50);
Back.Click += klikback; 
menu.AddView(Back);

SetContentView(upmenu);

Note, the 200 and 50 are in pixels, you should consider using dp instead. There are loads of post explaining how to convert those values.

Also the Bitmap in your picview is not disposed of and you are potentially leaking memory. So be careful with that.

Upvotes: 0

Related Questions