View的setOnClickListener的添加方法

1)第一种,也是最长见的添加方法(一下都以Button为例)

1 Button btn = (Button) findViewById(R.id.myButton);
2 btn .setOnClickListener(new View.OnClickListener() {
3 public void onClick(View v) {
4 //do something
5 }
6 });



2)第二种,下面这个方法较前一种稍微简单了一些,允许多个Buttons共享一个Listener。通过Switch控制对不同Button Click事件的响应方法:

复制代码
 1 Button btn = (Button) findViewById(R.id.mybutton);
2 Button btn2 = (Button) findViewById(R.id.mybutton2);
3 btn.setOnClickListener(handler);
4 btn2.setOnClickListener(handler);
5 View.OnClickListener handler = View.OnClickListener() {
6 public void onClick(View v) {
7 switch (v.getId()) {
8 case R.id.mybutton:
9 //do something
10 break;
11 case R.id.mybutton2:
12 //do something
13 break;
14 }
15 }
复制代码




3)第三种,直接将Clicklistener捆绑XML layout中的Views元素,在程序中定义的Listener方法需要带有一个View类型的参数:

复制代码
 1 <?xml version="1.0" encoding="utf-8"?>
2 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
3 android:orientation="vertical" android:layout_width="fill_parent"
4 android:layout_height="fill_parent">
5 <TextView android:layout_width="fill_parent"
6 android:layout_height="wrap_content" android:id="@+id/text"
7 android:text="@string/hello" />
8 <Button android:id="@+id/mybutton" android:layout_height="wrap_content"
9 android:layout_width="wrap_content" android:onClick="mybuttonlistener"></Button>
10 </LinearLayout>
复制代码

java代码:

1 Button btn = (Button) findViewById(R.id.mybutton);
2
3 public void mybuttonlistener(View target){
4 //do something
5 }

posted @   lingyun1120  阅读(92614)  评论(5编辑  收藏  举报
编辑推荐:
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
阅读排行:
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· 单线程的Redis速度为什么快?
· 展开说说关于C#中ORM框架的用法!
· Pantheons:用 TypeScript 打造主流大模型对话的一站式集成库
点击右上角即可分享
微信分享提示