在iOS中,我可以註冊多個目標+動作事件處理程序,例如像這樣的按鈕:如何在Android中註冊多個監聽器?
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(20, 40, 300, 40)];
[button setBackgroundColor:[UIColor blueColor]];
[button setTitle:@"Click Me!" forState:UIControlStateNormal];
[button addTarget:self action:@selector(handler1) forControlEvents:UIControlEventTouchUpInside];
[button addTarget:self action:@selector(handler2) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:button];
}
- (void)handler1 {
NSLog(@"Click handler 1"); // FIRES!
}
- (void)handler2 {
NSLog(@"Click handler 2"); // FIRES!
}
@end
我想實現的Java/Android的類似的東西,遺憾的是這不會工作至今爲第一個監聽被第二取代:
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button = (Button) findViewById(R.id.button);
button.setText("Click Me!");
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Log.d("Test", "Click handler 1"); // DOES NOT FIRE!
}
});
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Log.d("Test", "Click handler 2"); // FIRES!
}
});
}
}
我欣賞任何幫助&建議在Java/Android中實現相同!
你爲什麼要這麼做?你想通過這個實現什麼? –
我正在開發一個Android SDK,它需要在運行時向現有UI元素添加行爲。例如。發送點擊事件到我們的服務器... –