是否可以添加通过在Android中单击按钮调用的方法(不添加侦听器)
我想在单击按钮时调用方法。我找到了这个解决办法是否可以添加通过在Android中单击按钮调用的方法(不添加侦听器),android,wpf,button,click,Android,Wpf,Button,Click,我想在单击按钮时调用方法。我找到了这个解决办法 Button buttonOne = (Button) findViewById(R.id.button1); buttonOne.setOnClickListener(new Button.OnClickListener() { public void onClick(View v) { //Do stuff here } }); 但这个解决方案是可怕的 当出现以下情况时,是否可以在XML中添加方法调用:
Button buttonOne = (Button) findViewById(R.id.button1);
buttonOne.setOnClickListener(new Button.OnClickListener() {
public void onClick(View v) {
//Do stuff here
}
});
但这个解决方案是可怕的
当出现以下情况时,是否可以在XML
中添加方法调用:
<Button
android:id="@+id/actionButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/actionButtonUnclicked"
/>
是否已单击?类似于Windows Phone和WPF的XAML
?类似于android:onClick=clickMethod(),这里:
<?xml version="1.0" encoding="utf-8"?>
<!-- layout elements -->
<Button android:id="@+id/actionButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Click me!"
android:onClick="myButtonClick" />
<!-- even more layout elements -->
您可以使用android:onClick=“clickMethod” 在xml中:
<Button
android:id="@+id/actionButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/actionButtonUnclicked"
android:onClick="clickMethod"
/>
and in activity/ fragment add
PS:如果您想对多个按钮使用相同的方法
<Button
android:id="@+id/actionButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/actionButtonUnclicked"
android:onClick="clickMethod"
/>
and in activity/ fragment add
public void clickMethod(View v){
// do smth
}
public void clickMethod(View v){
// check for id
if(v.getId() == R.id.button1){
//operation for button 1 click
} else if(v.getId() == R.id.button2){ //operation for button 1 click
}
}