Android按钮单击事件的五种实现方式
程序员文章站
2022-05-18 15:33:33
1. 匿名内部类作为事件监听器 2. 内部类作为事件监听器 3. Activity本身作为事件监听器 4. 外部类作为事件监听器 5. 将事件处理方法直接绑定到标签 ......
-
匿名内部类作为事件监听器
public class mainactivity extends activity { private button button; @override protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.activity_main); button = (button) findviewbyid(r.id.button1); button.setonclicklistener(new onclicklistener() { @override public void onclick(view v) { system.out.println("匿名内部类作为事件监听器"); } }); } }
-
内部类作为事件监听器
public class mainactivity extends activity { private button button; @override protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.activity_main); button = (button) findviewbyid(r.id.button1); button.setonclicklistener(new buttononclicklistener()); } class buttononclicklistener implements onclicklistener{ @override public void onclick(view v) { system.out.println("内部类作为事件监听器"); } } }
-
activity本身作为事件监听器
public class mainactivity extends activity implements onclicklistener{ private button button; @override protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.activity_main); button = (button) findviewbyid(r.id.button1); button.setonclicklistener(this); } @override public void onclick(view v) { system.out.println("activity本身作为事件监听器"); } }
-
外部类作为事件监听器
public class mainactivity extends activity { private button button; @override protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.activity_main); button = (button) findviewbyid(r.id.button1); button.setonclicklistener(new buttononclicklistener()); } } class buttononclicklistener implements onclicklistener { @override public void onclick(view v) { system.out.println("外部类作为事件监听器"); } }
-
将事件处理方法直接绑定到标签
<button android:id="@+id/button1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="点击事件" android:onclick="onclick" />
public class mainactivity extends activity { @override protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.activity_main); } public void onclick(view v){ system.out.println("将事件处理方法直接绑定到标签"); } }