Michael Yuwono
Michael Yuwono

Reputation: 2617

Xamarin.Forms: How to Give Highlight Color to Label On Tap?

I know that I can make a Label clickable by using TapGesture. How can I give a highlight effect when the user is tapping it? (Either changing the Label's color or changing the Background Color just like when the user taps the Toolbar Items)

Upvotes: 1

Views: 2154

Answers (2)

ToolmakerSteve
ToolmakerSteve

Reputation: 21223

Here is a fix to Nick Pepper's answer, to properly restore color on UI thread.

private void OnTapped(object sender, EventArgs e)
{
    var label = sender as Label;
    label.TextColor = Color.Gray;
    Run.Task( () => {
        // Now we are on a background thread, can take as long as we want.
        // ... Do Something ...
        Device.BeginInvokeOnMainThread( () => {
            // Now we are back on main thread, can change UI.
            label.TextColor = Color.Black;
        });
    });
}

HOWEVER this won't change color to Gray until OnTapped fires - which is NOT the instant that user pushes down. So still isn't what user asked for.

Changing the color as soon as the user starts pushing is more involved. Might need to use Touch Tracking API.

OR use Visual State Manager.

Upvotes: 0

Nick Peppers
Nick Peppers

Reputation: 3251

You could simulate the effect with a TapGestureRecognizer by just changing the color of your label in your tapped method and back at the end.

private void OnTapped(object sender, EventArgs e)
{
    var label = sender as Label;
    label.TextColor = Color.Gray;
    //Do Something
    label.TextColor = Color.Black;
}

Although, styling a button might work better to handle the effect for you.

Upvotes: 1

Related Questions