Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Xamarin.Forms: wrong button text alignment after click (Android)

I have a problem with Xamarin.Forms (version 1.2.2) on Android (Nexus 5). The alignment of Button.Text is often not centered after performing a click.

In a short project, I figured out, that updating the UI causes the problem.

public class App
{
    public static Page GetMainPage()
    {   
        var label = new Label {
            Text = "label",
        };
        var buttonBad = new Button {
            Text = "buttonBad",
            Command = new Command(() => label.Text += "1"),
        };
        var buttonGood = new Button {
            Text = "buttonGood",
        };

        return new ContentPage { 
            Content = new StackLayout {
                Children = {
                    buttonBad,
                    buttonGood,
                    label,
                }
            }
        };
    }
}

A click on "buttonBad" (updating the label.Text) causes the text-alignment of this button to not be centered anymore. A click on "buttonGood" does not cause the problem.

Is there a good workaround to solve this problem?

This workaround seems to be too complicated: http://forums.xamarin.com/discussion/20608/fix-for-button-layout-bug-on-android

edit: A programatically edit of the UI also cases the bug. Changing the label.Text in an async method after a short waiting leads the "buttonGood" to align its text wrong after a click.

edit2: I created an example / test project on GitHub: https://github.com/perpetual-mobile/ButtonTextAlignmentBug.git The alignment is correct, when the StackLayout is replaced by an AbsolutLayout, but i need the StackLayout to work well.

like image 744
Maik Switalski Avatar asked Sep 26 '14 09:09

Maik Switalski


1 Answers

Ok, after hours of dealing with this silly bug, I resolved it by implementing a custom renderer and overriding ChildDrawableStateChanged:

public override void ChildDrawableStateChanged(Android.Views.View child) 
{
    base.ChildDrawableStateChanged(child); 
    Control.Text = Control.Text; 
}
like image 151
Mina Wissa Avatar answered Nov 11 '22 08:11

Mina Wissa