markpirvine
markpirvine

Reputation: 1592

Checkbox Size Xamarin Android

I've implemented checkboxes in my Xamarin Forms App using the following article:

https://alexdunn.org/2018/04/10/xamarin-tip-build-your-own-checkbox-in-xamarin-forms/

The only issue I have is that I can't set the size of Android, there is a question in the comments section, however there is no solution. No matter what I do the SizeRequest is always 64x64 - can anyone offer any suggestions or reason why I can't resize?

Upvotes: 0

Views: 1894

Answers (2)

Jader Oliveira
Jader Oliveira

Reputation: 341

Maybe I found a possible solution, check the steps below:

  • Add a BindableProperty called SizeRequest in the custom CheckBox control.
  • Create a method GetDefaultCheckBoxDrawable to get the default CheckBox drawable.
  • Change OnElementChanged method to clear and resize the text, set the width/height based on SizeRequest, reset the button drawable and set a new Background drawable with the default checkbox drawable.

AndroidCheckboxRenderer.cs:

private Drawable GetDefaultCheckBoxDrawable(Android.Views.View view)
{
    TypedValue value = new TypedValue();
    view.Context.Theme.ResolveAttribute(Android.Resource.Attribute.ListChoiceIndicatorMultiple, value, true);
    var origImg = view.Context.Resources.GetDrawable(value.ResourceId);
    var porterDuffColor = new Android.Graphics.PorterDuffColorFilter(Element.CheckColor.ToAndroid(), Android.Graphics.PorterDuff.Mode.SrcIn);
    origImg.SetColorFilter(porterDuffColor);
    return origImg;
}

protected override void OnElementChanged(ElementChangedEventArgs<CustomCheckbox> e)
{
    ...

    // CheckBox displays its height from the TEXT, as well as images.
    checkBox.Text = "";
    checkBox.SetTextSize(Android.Util.ComplexUnitType.Sp, 0);

    // Set the width and height based on SizeRequest
    if (Element.SizeRequest >= 0)
    {
        checkBox.SetWidth((int)Element.SizeRequest);
        checkBox.SetHeight((int)Element.SizeRequest);
    }

    // Reset the Button Drawable
    checkBox.SetButtonDrawable(null);
    // Set Background Drawable with the default CheckBox
    checkBox.SetBackgroundDrawable(GetDefaultCheckBoxDrawable(this));

    ...
}

Check out my GitHub for the full solution.

I hope this can help you.

Upvotes: 0

Jader Oliveira
Jader Oliveira

Reputation: 341

Did you try to use before the line 91, the code below in order to scale the control:

Control.ScaleX = 0.70;
Control.ScaleY = 0.70;

Upvotes: 2

Related Questions