How to create Custom Toggle Button in Vaadin (flow)
// Try this code...
// 1). Created custom Toggle Button using Vaadin Flow.
// 2). No dependencies.
// 3). You can change its color as per your requirement.
package com.vaadin.ui.customcomponents;
import com.vaadin.flow.component.orderedlayout.HorizontalLayout;
import com.vaadin.flow.component.orderedlayout.VerticalLayout;
public class CustomToggleButton extends VerticalLayout {
public static final String UNCHECKED_BACKGROUND_COLOR = "#CCCCCC";
public static final String CHECKED_BACKGROUND_COLOR = "#3375C2";
public static final String CIRCLE_COLOR = "#FFFFFF";
private boolean value = false;
public CustomToggleButton(int width, int height) {
this.setWidth(width + "px");
this.setMinWidth(width + "px");
this.setHeight(height + "px");
this.setMinHeight(height + "px");
this.setJustifyContentMode(JustifyContentMode.CENTER);
this.getStyle().set("background-color", UNCHECKED_BACKGROUND_COLOR);
this.getStyle().set("padding", "4px 8px 4px 8px");
this.getStyle().set("border-radius", "30px");
this.setAlignItems(Alignment.START);
HorizontalLayout horizontalLayout = new HorizontalLayout();
horizontalLayout.getStyle().set("background-color", CIRCLE_COLOR);
horizontalLayout.getStyle().set("border-radius", "100px");
horizontalLayout.setWidth(((width - 10) /2) + "px");
horizontalLayout.setHeight(((width - 10) /2) + "px");
this.add(horizontalLayout);
this.addClickListener(event -> {
changeValue();
});
}
public void setValue(boolean value) {
this.value = value;
if (this.value) {
this.getStyle().set("background-color", CHECKED_BACKGROUND_COLOR);
this.setAlignItems(Alignment.END);
}
else {
this.getStyle().set("background-color", UNCHECKED_BACKGROUND_COLOR);
this.setAlignItems(Alignment.START);
}
}
public boolean isValue() {
return value;
}
public void changeValue() {
value = !value;
if (this.value) {
this.getStyle().set("background-color", CHECKED_BACKGROUND_COLOR);
this.setAlignItems(Alignment.END);
}
else {
this.getStyle().set("background-color", UNCHECKED_BACKGROUND_COLOR);
this.setAlignItems(Alignment.START);
}
}
}
Comments
Post a Comment