简体   繁体   中英

In Delphi XE2 FireMonkey - How do i change the color of a button after pressing it

I just want to change the color of a button after I press it.

Do I have to use "styles" to do this or....?

You can change the button.StyleLookup property to change the style (color).

You need to add a new style to the Stylebook.

  1. Select 'Edit custom style ...' in the Right mouse button menu from a button.
  2. Change the Fill.Color property from the TRectangle items under the background:TRectangle
  3. Apply and Close Stylebook
  4. Clear button.stylelookup
  5. Change the button.stylelookup in your buttonclick to the new create style, when you didn't change the name its Button1Style1

Using Styles

An alternative to creating a different style and switching to that new style would be creating a custom style for the button and changing the color in that style at run time.

  1. Right-click the button and select 'Edit custom style...' from the main menu.
  2. Click Apply and Close in the style editor.

You've just created a custom style for the button. So when you edit it at run time, it will only affect that button.

Now, enter the following in your OnClick event to change the color at run time:

  var
    r: TRectangle;
  begin
    // Find the background TRectangle style element for the button
    r := (Button1.FindStyleResource('background') as TRectangle);
    if Assigned(r) then
    begin
      r.Fill.Color := claBlue;
    end;
  end;

Note: Add FMX.Objects to your uses clause if you don't already have it. That's where TRectangle is.

But wait...

You'll notice that the button's color changes back to the default when the mouse leave or enters the button. That's due to the animations. If you set the stylename properties for both of the TColorAnimation style elements in the style editor for the custom style, you can also set the color on those. For my example, I've named the TColorAnimations coloranimation1 and coloranimation2.

Here's the revised code:

var
  r: TRectangle;
  ca: TColorAnimation;
begin
  // Find the background TRectangle style element for the button
  r := (Button1.FindStyleResource('background') as TRectangle);
  if Assigned(r) then
  begin
    r.Fill.Color := claBlue;
  end;
  ca := (Button1.FindStyleResource('coloranimation1') as TColorAnimation);
  if Assigned(ca) then
  begin
    ca.StartValue := claBlue;
  end;
  ca := (Button1.FindStyleResource('coloranimation2') as TColorAnimation);
  if Assigned(ca) then
  begin
    ca.StopValue := claBlue;
  end;

Note: Add FMX.Ani to your uses clause for TColorAnimation.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM