首页 > 系统 > Android > 正文

Android Button按钮的四种点击事件

2019-10-23 19:53:06
字体:
来源:转载
供稿:网友

本文实例为大家分享了安卓Button按钮的四种点击事件,供大家参考,具体内容如下

第一种:内部类实现

1.xml里面先设置Button属性

<Button  android:id="+@id/button1";  android:layout_width="wrap_parent";  android:layout_height="wrap_parent"  android:text="按钮"/>

2.找到按钮

Button btn =(Button)findViewById(R.layout.button1)

3.给Button设置一个点击事件

btn.setOnClickListener(new MyClickListener()) //传入的是ClickListener参数所以我们必须去定义一个参数接口

4.定义一个类去实现 按钮需要的接口类型

public MianActivity extend Activity(){......private class MyClickListener()implent OnclickListener{ //当按钮被点击的时候调用 public void Onclick (View v){   //这里写点击事件方法    System.out.printLn("被点击了")    }} }

第二种:利用匿名内部类来实现

1.xml里面先设置Button属性

<Button  android:id="+@id/button1";  android:layout_width="wrap_parent";  android:layout_height="wrap_parent"  android:text="按钮"/>

2.找到按钮

Button btn =(Button)findViewById(R.layout.button1);

3.给Button设置一个点击事件

//匿名内部类public MianActivity extend Activity(){......btn.setOnClickListener(new OnClickListener(){ public void Onclick (View v){   //这里写点击事件方法    System.out.printLn("被点击了")    }} )   };

第三种:Activity实现OnclickListener接口适用于多个按钮情况

1.xml里面先设置Button属性

<Button  android:id="+@id/button1";  android:layout_width="wrap_parent";  android:layout_height="wrap_parent"  android:text="按钮"/><Button  android:id="+@id/button2";  android:layout_width="wrap_parent";  android:layout_height="wrap_parent"  android:text="按钮2"/>  <Button  android:id="+@id/button1";  android:layout_width="wrap_parent";  android:layout_height="wrap_parent"  android:text="按钮3"/>

2.找到按钮

Button btn =(Button)findViewById(R.layout.button1)Button btn2 =(Button)findViewById(R.layout.button2)Button btn3 =(Button)findViewById(R.layout.button3)

3.给Button设置一个点击事件

 

public MianActivity extend Activity implement OnClickListener(){   ...   ...   Button btn =(Button)findViewById(this);//this代表MainActivity   Button btn2 =(Button)findViewById(this)   Button btn3 =(Button)findViewById(this)   public void Onclick (View v){   //具体判断点击的是哪个按钮   switch(v.getId()){   case.R.id.button1://代表点击第一个按钮     TODO();//实现具体方法      break;   case.R.id.button2:      TODO();//实现具体方法      break;   case.R.id.button3:      TODO();//实现具体方法      break;      default:      break;   }    }    private void TODO(){     //具体方法    }}

第四种:在xml里面声明onclick

1.xml里面先设置Button属性

<Button  android:id="+@id/*button1*";  android:layout_width="wrap_parent";  android:layout_height="wrap_parent"  android:text="按钮"  android:onClick="click"/>

2.找到按钮

Button btn =(Button)findViewById(R.layout.button1)

3.声明一个方法,方法名和你要点击的这个按钮在xml布局中声明的Onclick属性一样

public void **click**(View v){  TODO();//实现具体方法}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持VEVB武林网。


注:相关教程知识阅读请移步到Android开发频道。
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表