android imagebutton click event in xml

╄→尐↘猪︶ㄣ 提交于 2019-12-10 20:15:16

问题


i define an imagebutton like this:

<ImageButton android:src="@raw/blaimage" /> 

now how can i also define which method should be called when the button is clicked.

in the android documentation it says that you can use onClick but it doesnt seem to compile for me.

 android:onClick="selfDestruct" 

and in the activity i have:

 public void selfDestruct(View view) {
     // Kabloey
 }

http://developer.android.com/reference/android/widget/Button.html


回答1:


just found out, what the problem was. i was targeting android 1.5 but this feature is only available since API level 4 which is 1.6




回答2:


When you get inflated your layout your button is available by id. So you can set any code to be executed when the button is clicked:

Button button = (Button) findViewByID(R.id.button_id);
button.setOnClickListener(new OnClickListener() {
 void onClick(...) {
   // your code here
}
};

Remember, that you should specify the id of your button like this(here it is button_id)



来源:https://stackoverflow.com/questions/4198345/android-imagebutton-click-event-in-xml

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!