class HelloWorld {
public static void main(String[] args) {
System.out.println("Start ------------");
UI ui = new UI();
ui.buttons[0].click();
ui.buttons[1].click();
ui.buttons[4].click();
}
static class UI {
int lastClickIndex = 0;
public Button[] buttons;
public UI() {
buttons = new Button[5];
for(int i = 0; i < 5; i++) {
Button item = new Button();
item.setButtonName("Button_" + i);
final int index = i;
item.setOnClickListener(() -> {
System.out.println("onClick = " + item.buttonName);
setActiveStyle(buttons[lastClickIndex], false);
setActiveStyle(item, true);
lastClickIndex = index;
});
buttons[i] = item;
}
}
public void setActiveStyle(Button button, boolean active) {
if (active) {
System.out.println("show BUTTON style " + button.buttonName);
} else {
System.out.println("default BUTTON style " + button.buttonName);
}
}
}
static class Button {
OnClickListener listener;
public String buttonName;
public interface OnClickListener {
void onClick();
}
public void setButtonName(String name) {
this.buttonName = name;
}
public void setOnClickListener(OnClickListener listener) {
this.listener = listener;
}
public void click() {
if (listener != null) listener.onClick();
}
}
}
【代码】[JAVA] example code 理解回調機制
最新推荐文章于 2024-08-16 23:08:28 发布