58

Xamarin Forms Tips Part 3: Change Randomly A View’s Color At Run-time

 5 years ago
source link: https://www.tuicool.com/articles/hit/ArmA7zQ
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
Era6nmB.png!web Change Randomly A View’s Color

Hi everyone, here is the third part of the Xamarin Forms Tips series. Today, we will look at how to change a view’s color randomly at run time. I implemented this feature in the “My Expenditures” application. As you can see on the screenshots above, the first letter of the user’s name changes color every time he runs the app. And it does so randomly. This post is all about implementing this functionality.

The app’s name is : My Expenditures. It is available on Play store and  Microsoft store . It provides you a smart way to manage you expenses and income. And very detailed stats about how you spend or make money. You can download and use it. You will also find in the app all the features I talk about here.

Change Randomly A View’s Color At Run-time

We will change the color of the text of a label at run-time. This feature is implemented using markup extensions. We predefined a set of colors which we randomly assign to the view. This is extremely simple and here is the code for it.

[ContentProperty("TextColor")]
public class RandomColorExtension : IMarkupExtension
{
    /// <summary>
    /// Send a Random Color to be displayed by the user.
    /// </summary>
    /// <param name="serviceProvider"></param>
    /// <returns></returns>
    public object ProvideValue(IServiceProvider serviceProvider)
    {
        var colors = new List<Color>
        {
            Color.SkyBlue,
            Color.Salmon,
            Color.SandyBrown,
            Color.SeaGreen,
            Color.Turquoise
        };
        
        return colors[new Random().Next(0,4)];
    }
}

After implementing the  markup extension, applying it to a label is very easy.

<Label
                       FontAttributes="Bold"
                       FontSize="{StaticResource ExtraHugeSize}"
                       HorizontalOptions="Center"
                       Text="{Binding UserInitial, Mode=TwoWay}"
                       TextColor="{markupExtensions:RandomColorExtension}"
                       VerticalOptions="Center" />

Conclusion

You can randomly change the color of your controls easily at runtime. This feature can help you improve UX. I applied it to a label, but you could apply it to any other control.

You may be interestedby this post about numeric entry recipes. Learn more about markup extensions here .

Follow me on social media and stay updated


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK